Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 582
Pentium10 Avatar asked Jun 22 '10 06:06

Pentium10


People also ask

How do I get the parent directory of a file?

Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory.

What is the parent directory of a file?

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.

Can touch create directories?

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.

How do you create a directory if it does not exist in Java?

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.


1 Answers

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.

like image 102
Jon Skeet Avatar answered Oct 18 '22 01:10

Jon Skeet