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?
Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory.
With a directory, a parent directory is a directory containing the current directory. For example, in the MS-DOS path below, the "Windows" directory is the parent directory of the "System32" directory, and C:\ is the root directory.
touch is not able to create directories, you need mkdir for that. However, mkdir has the useful -p / --parents option which creates a full directory structure. If you think you will need this more often and don't want to type the path twice every time, you can also make a Bash function or a script for it.
Create a Directory if it Does Not Exist You can use the Java File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose. The mkdir() method creates a single directory if it does not already exist.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With