Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a proper way to check for file/directory existence in Java?

Tags:

java

file-io

Code:

String dir = //Path to the  directory
File saveDir = new File(dir);
//Here comes the existence check
if(!saveDir.exists())
  saveDir.mkdirs();

This part of code is used to save files with a given directory path to file system. Before saving i want to check whether the given save directory exists. However the existence check do not seem to work in the way that i wanted. Without removing the if clause the desired directories are not created.I came across to this interesting stack question while searching for my problem. Alternative to File.exists() in Java. As i understand java.io has this problem.

Is there a proper and safe way to check the existance of a directory or resource while doing file operations?

like image 695
fgakk Avatar asked Nov 03 '11 14:11

fgakk


People also ask

How do you check if a directory exists or not in Java?

File. exists() is used to check whether a file or a directory exists or not. This method returns true if the file or directory specified by the abstract path name exists and false if it does not exist.

Which method is used to check file existence in Java?

File exists() method in Java with examples The exists() function is a part of the File class in Java. This function determines whether the is a file or directory denoted by the abstract filename exists or not. The function returns true if the abstract file path exists or else returns false.

Which method is used to check that the path is a directory?

os. path. isdir() method in Python is used to check whether the specified path is an existing directory or not.


2 Answers

new File(dir).getCanonicalFile().isDirectory();  

Skeleton for your reference:-

File f = new File("....");
if (!f.exists()) {
    // The directory does not exist.
    ...
} else if (!f.isDirectory()) {
    // It is not a directory (i.e. it is a file).
    ... 
}
like image 131
Siva Charan Avatar answered Nov 10 '22 06:11

Siva Charan


Well, even if the check would be correct, you can never be sure that the directory still exists after the if condition has been evaluated. Another process or user can just create/remove it. So you have to check if the operation fails (possibly catching the appropriate exception) anyway.

So you shouldn't rely on checks and expect the worst case always. (Well, the checks may be useful for preventing you from doing something unnecessary, or for asking user for confirmation etc. But they don't guarantee anything.)

like image 36
Vlad Avatar answered Nov 10 '22 05:11

Vlad