程序员 - android 内部存储自定义文件夹写入
PHP中文网
PHP中文网 2017-04-17 12:01:02
[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自定义文件夹 并在文件夹中进行文件操作呢?

PHP中文网
PHP中文网

认证0级讲师

全部回复(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();
    }
PHPz

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号