Is there a way to check if a file / directory exists in Java?

The code:

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

This piece of code is used to save files with a given directory in the file system. Before saving, I want to check if this save directory exists. However, checking for availability does not work the way I wanted. Without deleting the if clause, the desired directories are not created. I came across this interesting stack question while searching for my problem. Alternative to File.exists () in Java . As I understand it, java.io has this problem.

Is there a correct and safe way to check the existence of a directory or resource when performing file operations?

+6
source share
4 answers

Well, even if the check is correct, you can never be sure that the directory still exists after the if condition has been evaluated. Another process or user can simply create or delete it. Thus, you should check if the operation has completed (possibly catch the corresponding exception).

Therefore, you should not rely on verification and always expect the worst. (Well, checks can be useful so that you do not do something unnecessary or ask the user for confirmation, etc. But they do not guarantee anything.)

+6
source
 new File(dir).getCanonicalFile().isDirectory(); 

Skeleton for reference: -

 File f = new File("...."); if (!f.exists()) { // The directory does not exist. ... } else if (!f.isDirectory()) { // It is not a directory (ie it is a file). ... } 
+27
source

Just call mkdirs . It will not overwrite existing directories so your check is not needed (and in any case unreliable).

+1
source

FileChannel.lock () does exactly what you want if it is not another thread in the JVM that deletes the directory while you are using it. This thing requires locking the OS in the file / folder on behalf of the JVM process, therefore, while other processes will not be able to access this directory, threads in the JVM can.

0
source

Source: https://habr.com/ru/post/900700/


All Articles