【发布时间】:2020-08-29 22:00:55
【问题描述】:
我正在尝试将所有 .java-files 放入 directory(已给出)及其所有子目录中。这就是我想出的:
public static void getJavaFiles(Path path) {
DirectoryStream<Path> stream = null;
try {
stream = Files.newDirectoryStream(path);
for (Path entry : stream) {
if (Files.isRegularFile(entry)) {
if(entry.getFileName().toString() == "*.java") {
System.out.println(entry.getFileName().toString());
};
} else if (Files.isDirectory(entry)) {
getJavaFiles(entry);
}
}
} catch (IOException e) {
throw new RuntimeException(String.format("error reading folder %s: %s", path, e.getMessage()), e);
} finally {
if(stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
}
不幸的是,entry.getFileName().toString() == "*.java" 并没有像我想象的那样工作。我得到了所有文件,但我如何只得到 .java 文件?
【问题讨论】:
-
你必须使用
.matches(.*\\.java")。该比较有两个问题 - 第一个是您使用equals方法比较字符串,第二个是该字符串将仅匹配名为“*.java”的文件,而不是匹配该模式的文件 -
@user 那么正确的方法是什么?
-
你只需要
if(entry.getFileName().toString().contains(".java"))。或者,如果必须在末尾,.endsWith(".java") -
@WiktorStribiżew 就是这样!完美运行。谢谢。
-
.endsWith(".java")将确保字符串以.java结尾