天天看点

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

继续阅读