Pentium10
Pentium10

Reputation: 208042

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?

Upvotes: 124

Views: 60645

Answers (4)

Mahozad
Mahozad

Reputation: 24742

Searching for a Kotlin solution this generally-titled question pops up.
So, for Kotlin 1.9.0 and newer there is a new createParentDirectories() method on Path class:

Path("my/path/to/file.txt").createParentDirectories()

Upvotes: 1

Ted
Ted

Reputation: 1611

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

Upvotes: 27

Zoltán
Zoltán

Reputation: 22206

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

Upvotes: 21

Jon Skeet
Jon Skeet

Reputation: 1503599

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.

Upvotes: 182

Related Questions