如何检查文件夹是否存在


199

我正在使用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());
    }


}

2
我想知道为什么您要检查文件夹是否存在。仅仅因为选中时文件夹存在并不意味着创建时文件夹存在DirectoryStream,更不用说遍历文件夹条目时了。
奥斯瓦尔德

Answers:


262

使用java.nio.file.Files

Path path = ...;

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

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

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

还有一种方法notExists

if (Files.notExists(path)) {

30
另外,请注意,两者Files.exists(path)Files.notExists(path)都可以同时返回false!这意味着Java无法确定该路径是否实际存在。
桑奇特

O_O @Sanchit你有很强的说法要说吗?
理查德

6
该文件说。:) 链接检查notExists方法不能真正正确地链接它。
桑契特2014年

13
Files.isDirectory(Path,LinkOption);
Kanagavelu Sugumar 2014年

2
@LoMaPh !Files.exists(path)Files.notExists(path)不是100%,同样的事情。当Java无法确定文件是否存在时,第一个将返回true,第二个将返回false
Jesper

205

非常简单:

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

如果要确定它是一个目录,请执行以下操作:

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

40
正确答案,但有一点注意:if(f.isDirectory()) {...}就足够了,因为它可以检查是否存在。
G. Demecki 2015年

3
这不能回答OP的问题。java.io.file不是OP所指的“新Java 7 IO功能”的一部分。java.nio.fileJava 7中引入的软件包提供PathsFiles类。这里的其他答案正确地解释了如何使用这些较新的类来解决OP问题。
多伦·金

53

要检查新IO是否存在目录:

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

isDirectory返回true文件是否为目录;false如果文件不存在,不是目录,或者无法确定文件是否为目录。

请参阅:文档


6

您需要将Path转换为File并测试其存在性:

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

5

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

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");
        }

4

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


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

}

1
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”
Oleg Ushakov,

1

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

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.type.handling.GroovyCastException:无法将类为“ org.codehaus.groovy.runtime.GStringImpl”的对象“ Z:\\ tierWe bServices \ Deploy \ new.txt”转换为类“ java.nio” .fi le.Path'org.codehaus.groovy.runtime.typehandling.GroovyCastException:无法将类为'org.codehaus.groovy.runtime.GStringImpl'的对象'Z:\\ tierWebService s \ Deploy \ new.txt'转换为类'java.nio.file.Path'
吉荣胡锦涛

0

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
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.