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

后端 未结 4 1853
不思量自难忘°
不思量自难忘° 2021-01-12 23:15

Code:

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


        
相关标签:
4条回答
  • 2021-01-12 23:43

    Just make the call to mkdirs. It will not overwrite existing directories so really, your check is unecessary (and in any case, unreliable).

    0 讨论(0)
  • 2021-01-12 23:44

    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.)

    0 讨论(0)
  • 2021-01-12 23:57

    FileChannel.lock() does just what you want as long as it's not another thread in the JVM that's deleting the directory while you're using in. This thing demandes a OS lock on a file/folder on behalf of the JVM process, so while other processes will not be able to access that directory, threads in the JVM can.

    0 讨论(0)
  • 2021-01-12 23:59
    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).
        ... 
    }
    
    0 讨论(0)
提交回复
热议问题