Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write elegant code using File.mkdirs() in java?

Tags:

java

file

io

mkdirs

I need a directory to save files but I am not sure whether it exists.
So I need to check if it exists first, and create it if necessary.

File saveDir = new File("/tmp/appname/savedir/");
if(!saveDir.exists()){
    saveDir.mkdirs(); 
}

As above, there is a question.
Method "saveDir.exists()" returns a boolean value which indicates if the file path exists.

Of course, I could write some redundant and ugly code to work.

Is there a way to write some elegant code to achieve this goal?

like image 446
kino lucky Avatar asked Nov 29 '22 02:11

kino lucky


2 Answers

is your question about "redundant" check-directory-exist code, or you need to create a directory and all missing parent directory?

I believe both can be easily done by using FileUtils in Apache Commons IO:

FileUtils.forceMkDir(new File("/some/missing/parent/directory/foo"));
like image 148
Adrian Shum Avatar answered Dec 04 '22 08:12

Adrian Shum


There is always

if(!file.exists() && !file.mkDirs()) { // handle the failed to create situation... }
like image 40
Nathaniel Avatar answered Dec 04 '22 07:12

Nathaniel