android 内部存储自定义文件夹写入

发布于 2022-08-29 23:25:43 字数 608 浏览 9 评论 0

    try {
        f = new File(this.getFilesDir().toString() + File.separator + "texts" + File.separator + 1 + ".txt");
        fos = new FileOutputStream(f);
        fos.write("test".getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

代码中f生成的路径是 data/data/com../files/texts/1.txt , 运行中不抛出任何异常,但是文件却并没有被创建

请问如何才能实现在internal storage自定义文件夹 并在文件夹中进行文件操作呢?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沉溺在你眼里的海 2022-09-05 23:25:43

FileOutputStream 不依赖文件是否存在,如果存在就打开文件,不存在就创建文件并打开。
问题原因可能在于"texts"目录没有创建和File.toString()。

try{
File textsDir = new File(this.getFilesDir().getAbsolutePath() + File.separator + "texts");
if(!textsDir.exists()){
  textsDir.mkdir();
}

f = new File(textsDir, "1.txt");

fos = new FileOutPutStream(f);
...
}catch(...)...

没有亲测,请自己尝试。

凉城凉梦凉人心 2022-09-05 23:25:43

确定没抛出任何异常?

    try {
        f = new File(this.getFilesDir().toString() + File.separator + 1 + ".txt");// texts路径不存在,调用createNewFile()会抛出IOException
        f.createNewFile();
        fos = new FileOutputStream(f);// 原代码这步会抛FileNotFoundException
        fos.write("test".getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
轮廓§ 2022-09-05 23:25:43

@旱獭先生 正解。文件夹不存在的时候,请先创建目录

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文