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

    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自定义文件夹 并在文件夹中进行文件操作呢?

阅读 11.6k
3 个回答

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(...)...

没有亲测,请自己尝试。

确定没抛出任何异常?

    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();
    }

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题