javadirectoryjava-iojava-nio

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?


Solution

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