How to check if a folder exists

后端 未结 10 1832
滥情空心
滥情空心 2020-11-28 21:21

I am playing a bit with the new Java 7 IO features, actually I trying to receive all the xml files of a folder. But this throws an exception when the folder does not exist,

相关标签:
10条回答
  • 2020-11-28 21:58

    To check if a directory exists with the new IO:

    if (Files.isDirectory(Paths.get("directory"))) {
      ...
    }
    

    isDirectory returns true if the file is a directory; false if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.

    See: documentation.

    0 讨论(0)
  • 2020-11-28 22:04

    From SonarLint, if you already have the path, use path.toFile().exists() instead of Files.exists for better performance.

    The Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist.

    The same goes for Files.notExists, Files.isDirectory and Files.isRegularFile.

    Noncompliant Code Example:

    Path myPath;
    if(java.nio.Files.exists(myPath)) {  // Noncompliant
        // do something
    }
    

    Compliant Solution:

    Path myPath;
    if(myPath.toFile().exists())) {
        // do something
    }
    
    0 讨论(0)
  • 2020-11-28 22:09

    We can check files and thire Folders.

    import java.io.*;
    public class fileCheck
    {
        public static void main(String arg[])
        {
            File f = new File("C:/AMD");
            if (f.exists() && f.isDirectory()) {
            System.out.println("Exists");
            //if the file is present then it will show the msg  
            }
            else{
            System.out.println("NOT Exists");
            //if the file is Not present then it will show the msg      
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-28 22:11

    Using java.nio.file.Files:

    Path path = ...;
    
    if (Files.exists(path)) {
        // ...
    }
    

    You can optionally pass this method LinkOption values:

    if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
    

    There's also a method notExists:

    if (Files.notExists(path)) {
    
    0 讨论(0)
提交回复
热议问题