android file.mkdir()一直返回false問題

        今天想寫本地日誌,結果寫文件的時候一直失敗,報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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章