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

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?


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.


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