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?
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();
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()
Have you tried this?
I don't know of a single method call that will do this, but it's pretty easy as two statements.