获取目录和所有子目录中的Java文件[重复] 。

问题描述 投票:0回答:1

我想把所有的 .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 文件?

java regex nio java-io
1个回答
1
投票

你可以看看这个。

if(entry.getFileName().endsWith(".java"))
© www.soinside.com 2019 - 2024. All rights reserved.