天天看點

java建立檔案和檔案夾時報錯java.io.FileNotFoundException:XXX (Is a directory)

1.建立自定義名檔案夾 ,注意"/"

File dir = new File(getExternalFilesDir(null).getPath()+"/自定義檔案夾名");
if(!dir.exists()){
    dir.mkdir();
}
           

2.建立檔案

File file = new File(dir+"/","檔案名加格式");
if (!file.exists()){
    try {
        file.createNewFile();
    } catch (IOException e) {
         e.printStackTrace();
    }
}
           

3.File類的構造函數中:File(File, String)構造函數建立的對象是檔案夾,File(String, String)函數建立的對象才是檔案

4.mkdir()和mkdirs()都是建立檔案夾的,加s的方法會把路徑中不存在的父檔案夾都建立出來

5.creatNewFile()才是建立檔案的

6.執行個體:

//建立TemporaryStorage檔案夾
File dir = new File(getExternalFilesDir(null).getPath()+"/voice/TemporaryStorage");
if (!dir.exists()){
    dir.mkdir();
}
String time = String.valueOf(System.currentTimeMillis());   //擷取檔案建立時間
//在TemporaryStorage檔案夾中建立音頻檔案
final File file = new File(dir+"/", time + ".pcm");
if (!file.exists()){
    try {
         file.createNewFile();
    } catch (IOException e) {
         e.printStackTrace();
    }
}
           

繼續閱讀