使用时
file.createNewFile();
Run Code Online (Sandbox Code Playgroud)
我得到以下异常
java.io.IOException: Parent directory of file does not exist: /.../pkg/databases/mydb
Run Code Online (Sandbox Code Playgroud)
我想知道是否有createNewFile创建缺少的父目录?
Jon*_*eet 135
你试过这个吗?
file.getParentFile().mkdirs();
file.createNewFile();
Run Code Online (Sandbox Code Playgroud)
我不知道一个单独的方法调用会做到这一点,但它很容易作为两个语句.
Ted*_*Ted 17
从 java7 开始,您还可以使用 NIO2 API:
void createFile() throws IOException {
Path fp = Paths.get("dir1/dir2/newfile.txt");
Files.createDirectories(fp.getParent());
Files.createFile(fp);
}
Run Code Online (Sandbox Code Playgroud)
Zol*_*tán 11
如果您确定要创建文件的路径字符串包含父目录,即如果您确定路径是表单,则Jon的答案有效<parent-dir>/<file-name>.
如果没有,即它是表格的相对路径<file-name>,那么getParentFile()将返回null.
例如
File f = new File("dir/text.txt");
f.getParentFile().mkdirs(); // works fine because the path includes a parent directory.
File f = new File("text.txt");
f.getParentFile().mkdirs(); // throws NullPointerException because the parent file is unknown, i.e. `null`.
Run Code Online (Sandbox Code Playgroud)
因此,如果您的文件路径可能包含或不包含父目录,则使用以下代码可以更安全:
File f = new File(filename);
if (f.getParentFile() != null) {
f.getParentFile().mkdirs();
}
f.createNewFile();
Run Code Online (Sandbox Code Playgroud)