Is there a correct way to check the existence of files / directories in Java?
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 the code is used to save a file with a given directory path to the file system Before saving, I want to check whether the given save directory exists However, existence checking does not seem to work as I want If the if clause is not removed, the required directory will not be created I encountered this interesting stack problem while searching for my problem Alternative to File. exists() in Java. As far as I know, Java I have this problem
Is there a correct and safe way to check the existence of directories or resources during file operations?
Solution
Well, even if the check is correct, after the if condition is evaluated, you still can't determine whether the directory still exists Another process or user can create / delete it Therefore, you must check whether the operation fails (corresponding exceptions may be caught)
Therefore, you should not rely on inspection and always expect the worst (well, checking may help prevent you from doing something unnecessary, or asking users to confirm, etc. but they don't guarantee anything.)