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?
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"));
There is always
if(!file.exists() && !file.mkDirs()) { // handle the failed to create situation... }
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