android file.mkdir()一直返回false问题

本文详细解析了在Android开发中遇到的文件创建失败问题,介绍了正确的文件路径创建方法,包括使用context.getExternalFilesDir()和context.getCacheDir(),并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        今天想写本地日志,结果写文件的时候一直失败,报FileNotFound错误,很明显,就是文件创建失败的问题了,debug了一下,发现在创建路径的时候,file.mkdirs()就出问题了(这个方法相对file.mkdir()还多了检测是否存在,偷懒必备),检查了一下,发现权限都没有问题,跑去developer看一下,发现现在不能直接用

Environment.getExternalStorageDirectory();

方法来创建路径或文件了,现在用的是context.getExternalFilesDir()或者context.getCacheDir()

        完整的使用方式如下

String file_path = context.getExternalCacheDir() + File.separator + fileDirectoy;
new File(file_path).mkdirs();//会自动判断路径是否存在如果不存在,创建路径
String fileName = file_path + File.separator + "自定义文件名";
File file = new File(fileName);
if(!file.exists()){
    try{
        file.createNewFile();
    }catch (IOException e){
        Log.e("ALeeObj", e.toString());
    }
}


可以用这个来判断文件路径是否还可用

boolean isPathAvailable = Environment.getExternalStorageState(filePath).equals(Environment.MEDIA_MOUNTED);//返回true表示改路径可读也可写

当然你也可以用getExternalFilesDir方法,在这里不建议用getFilesDir()和getCacheDir()方法,实测了一下文件不知道创建到哪了,暂时没有找到

还有getExternalCacheDir()创建的文件路径在  根目录/Android/data/你的applicationId/cache/

developer getExternalCacheDir方法说明链接: 

https://developer.android.google.cn/reference/kotlin/android/content/Context?hl=en#getExternalCacheDir()

developer Enviroment类说明链接:

https://developer.android.google.cn/reference/kotlin/android/os/Environment.html#getExternalStorageState(java.io.File)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值