如何检查文件夹是否存在?

2022-08-31 05:44:11

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

答案 1

用:java.nio.file.Files

Path path = ...;

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

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

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

还有一种方法:notExists

if (Files.notExists(path)) {

答案 2

很简单:

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

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

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

推荐