How to create a new file together with missing parent directories?

Java

Java Problem Overview


When using

file.createNewFile();

I get the following exception

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

I am wondering is there a createNewFile that creates the missing parent directories?

Java Solutions


Solution 1 - Java

Have you tried this?

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

I don't know of a single method call that will do this, but it's pretty easy as two statements.

Solution 2 - Java

Jon's answer works if you are certain that the path string with which you are creating a file includes parent directories, i.e. if you are certain that the path is of the form <parent-dir>/<file-name>.

If it does not, i.e. it is a relative path of the form <file-name>, then getParentFile() will return null.

E.g.

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`.

So if your file path may or may not include parent directories, you are safer with the following code:

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

Solution 3 - Java

As of java7, you can also use NIO2 API:

void createFile() throws IOException {
    Path fp = Paths.get("dir1/dir2/newfile.txt");
    Files.createDirectories(fp.getParent());
    Files.createFile(fp);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPentium10View Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaZoltánView Answer on Stackoverflow
Solution 3 - JavaTedView Answer on Stackoverflow