我正在尝试一些新的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());
    }
}

当前回答

使用java.nio.file.Files:

Path path = ...;

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

你可以选择将LinkOption值传递给这个方法:

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

还有一个方法notExists:

if (Files.notExists(path)) {

其他回答

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

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

你需要将路径转换为文件并测试是否存在:

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

使用java.nio.file.Files:

Path path = ...;

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

你可以选择将LinkOption值传递给这个方法:

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

还有一个方法notExists:

if (Files.notExists(path)) {
File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;
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;
  }

}