我正在尝试一些新的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());
}
}
从SonarLint,如果你已经有路径,使用path. tofile ().exists()而不是Files。为了更好的性能而存在。
这些文件。在JDK 8中,exists方法的性能明显较差,当用于检查实际上不存在的文件时,会显著减慢应用程序的运行速度。
文件也是如此。notExists,文件。isDirectory and Files.isRegularFile。
不合规代码示例:
Path myPath;
if(java.nio.Files.exists(myPath)) { // Noncompliant
// do something
}
兼容的解决方案:
Path myPath;
if(myPath.toFile().exists())) {
// do something
}
从SonarLint,如果你已经有路径,使用path. tofile ().exists()而不是Files。为了更好的性能而存在。
这些文件。在JDK 8中,exists方法的性能明显较差,当用于检查实际上不存在的文件时,会显著减慢应用程序的运行速度。
文件也是如此。notExists,文件。isDirectory and Files.isRegularFile。
不合规代码示例:
Path myPath;
if(java.nio.Files.exists(myPath)) { // Noncompliant
// do something
}
兼容的解决方案:
Path myPath;
if(myPath.toFile().exists())) {
// do something
}