如何在缺少父目录的情况下创建新文件?


98

使用时

file.createNewFile();

我得到以下异常

java.io.IOException: Parent directory of file does not exist: /.../pkg/databases/mydb

我想知道是否有一个createNewFile创建丢失的父目录?

Answers:


150

你有试过吗?

file.getParentFile().mkdirs();
file.createNewFile();

我不知道会执行此操作的单个方法调用,但是作为两个语句非常简单。


如果该文件是用包含父目录,即路径字符串创建这只能new File("file.txt").getParentFile()返回nullnew File("dir/file.txt").getParentFile()返回一样new File("dir")
佐尔坦

1
的确,mkdirs如果您要创建的文件不在不存在的目录中,则不需要,但我的用例是我正在创建多个文件,其中有些文件具有父目录,而另一些文件没有。
佐尔坦

14

如果您确定用来创建文件的路径字符串包括父目录,那么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`.

因此,如果您的文件路径可能包含也可能不包含父目录,那么使用以下代码会更安全:

File f = new File(filename);
if (f.getParentFile() != null) {
  f.getParentFile().mkdirs();
}
f.createNewFile();

由于许多原因,您应该始终包含路径。系统还应该如何知道您要将文件放在哪里?
NikkyD 2015年

@NikkyD对不起,我不太理解您的评论。在我的回答中,我并不是说您不包含路径,而是所传递的路径可能不包含父目录。答案中也有此类路径的示例。
佐尔坦

7

从java7开始,您还可以使用NIO2 API:

void createFile() throws IOException {
    Path fp = Paths.get("dir1/dir2/newfile.txt");
    Files.createDirectories(fp.getParent());
    Files.createFile(fp);
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.