【问题标题】:How to check if a folder exists?如何检查文件夹是否存在?
【发布时间】:2013-03-12 09:03:57
【问题描述】:

我正在尝试使用新的 Java 7 IO 功能。实际上,我正在尝试检索文件夹中的所有 XML 文件。但是,当文件夹不存在时,这会引发异常。如何使用新的 IO 检查文件夹是否存在?

public UpdateHandler(String release) {
    log.info("searching for configuration files in folder " + release);
    Path releaseFolder = Paths.get(release);
    try(DirectoryStream<Path> stream = Files.newDirectoryStream(releaseFolder, "*.xml")){
    
        for (Path entry: stream){
            log.info("working on file " + entry.getFileName());
        }
    }
    catch (IOException e){
        log.error("error while retrieving update configuration files " + e.getMessage());
    }
}

【问题讨论】:

  • 我想知道您为什么要检查该文件夹是否存在。仅仅因为您检查时该文件夹存在并不意味着该文件夹在您创建DirectoryStream时就存在,更不用说在您遍历文件夹条目时。

标签: java


【解决方案1】:

使用java.nio.file.Files

Path path = ...;

if (Files.exists(path)) {
    // ...
}

您可以选择传递此方法LinkOption 值:

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

还有一个方法notExists

if (Files.notExists(path)) {

【讨论】:

  • 另外,请注意Files.exists(path)Files.notExists(path) 可以同时返回false!这意味着 Java 无法确定路径是否实际存在。
  • O_O @Sanchit 你有什么强有力的论据要说吗?
  • 文档是这么说的。 :) link 检查 notExists 方法不能真正正确链接。
  • Files.isDirectory(Path, LinkOption);
  • @LoMaPh !Files.exists(path)Files.notExists(path) 不是 100% 相同的东西。当Java无法判断文件是否存在时,第一个会返回true,第二个会返回false
【解决方案2】:

很简单:

new File("/Path/To/File/or/Directory").exists();

如果你想确定它是一个目录:

File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
   ...
}

【讨论】:

  • 正确答案,但有一个小提示:if(f.isDirectory()) {...} 就足够了,因为它也检查存在。
  • 这不能回答 OP 的问题。 java.io.file 不是 OP 所指的“新 Java 7 IO 功能”的一部分。在 Java 7 中引入的 java.nio.file 包提供了 PathsFiles 类。此处的其他答案正确解释了如何使用这些较新的类来解决 OPs 问题。
  • @DoronGold 感谢您的及时回复!我会接受你所说的。
【解决方案3】:

使用新 IO 检查目录是否存在:

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

isDirectory 如果文件是目录则返回truefalse如果文件不存在,不是目录,或者无法确定文件是否是目录。

请参阅:documentation

【讨论】:

    【解决方案4】:

    从你的文件夹目录的字符串生成一个文件

    String path="Folder directory";    
    File file = new File(path);
    

    存在使用方法。
    如果你想生成你应该使用 mkdir() 的文件夹

    if (!file.exists()) {
                System.out.print("No Folder");
                file.mkdir();
                System.out.print("Folder created");
            }
    

    【讨论】:

      【解决方案5】:

      您需要将您的 Path 转换为 File 并测试是否存在:

      for(Path entry: stream){
        if(entry.toFile().exists()){
          log.info("working on file " + entry.getFileName());
        }
      }
      

      【讨论】:

        【解决方案6】:

        不需要单独调用exists()方法,isDirectory()会隐式检查目录是否存在。

        【讨论】:

          【解决方案7】:
          import java.io.File;
          import java.nio.file.Paths;
          
          public class Test
          {
          
            public static void main(String[] args)
            {
          
              File file = new File("C:\\Temp");
              System.out.println("File Folder Exist" + isFileDirectoryExists(file));
              System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));
          
            }
          
            public static boolean isFileDirectoryExists(File file)
          
            {
              if (file.exists())
              {
                return true;
              }
              return false;
            }
          
            public static boolean isDirectoryExists(String directoryPath)
          
            {
              if (!Paths.get(directoryPath).toFile().isDirectory())
              {
                return false;
              }
              return true;
            }
          
          }
          

          【讨论】:

            【解决方案8】:
            File sourceLoc=new File("/a/b/c/folderName");
            boolean isFolderExisted=false;
            sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;
            

            【讨论】:

            • sourceLoc.isDirectory() 返回布尔结果。无需使用“sourceLoc.isDirectory() == true”
            【解决方案9】:

            我们可以检查文件和三个文件夹。

            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      
                    }
                }
            }
            

            【讨论】:

            • 似乎不适用于网络共享文件。捕获:org.codehaus.groovy.runtime.typehandling.GroovyCastException:无法将对象 'Z:\\tierWe bServices\Deploy\new.txt' 与类 'org.codehaus.groovy.runtime.GStringImpl' 转换为类 'java.nio .file.Path' org.codehaus.groovy.runtime.typehandling.GroovyCastException:无法将对象 'Z:\\tierWebService s\Deploy\new.txt' 与类 'org.codehaus.groovy.runtime.GStringImpl' 转换为类'java.nio.file.Path'
            【解决方案10】:

            来自SonarLint,如果您已经有了路径,请使用path.toFile().exists() 而不是Files.exists 以获得更好的性能。

            Files.exists 方法在 JDK 8 中的性能明显较差,并且在用于检查实际不存在的文件时会显着降低应用程序的速度。

            Files.notExistsFiles.isDirectoryFiles.isRegularFile 也是如此。

            不合规代码示例:

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

            合规解决方案:

            Path myPath;
            if(myPath.toFile().exists())) {
                // do something
            }
            

            【讨论】:

              猜你喜欢
              • 2011-11-15
              • 1970-01-01
              • 2011-02-21
              • 2013-08-24
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2010-12-10
              相关资源
              最近更新 更多