-1

I am trying to get all .java-files in a directory (that is given) and all its subdirectories . This is what Ive come up:

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) {

            }
        }
    }   

}

Unfortunately entry.getFileName().toString() == "*.java" is not working how I thought it would. I get all the files but how do I get only the .java files ?

Chris
  • 1,828
  • 6
  • 40
  • 108
  • You'd have to use `.matches(.*\\.java")`. There are 2 issues with that comparison - the first is that you use the `equals` method to compare strings, and the second is that that string will only match files called "*.java" exactly, not files matching that pattern – user May 13 '20 at 15:58
  • @user what would be the correct way to do it then? – Chris May 13 '20 at 15:59
  • 2
    You just need `if(entry.getFileName().toString().contains(".java"))`. Or, if it must be at the end, `.endsWith(".java")` – Wiktor Stribiżew May 13 '20 at 16:01
  • @WiktorStribiżew that was it! Works perfectly. thanks. – Chris May 13 '20 at 16:03
  • @WiktorStribiżew oh wait, actually not. what about this file: example.java.txt ? This should not be detected – Chris May 13 '20 at 16:04
  • 1
    `.endsWith(".java")` will make sure the string ends with `.java` – Wiktor Stribiżew May 13 '20 at 16:05

1 Answers1

1

You can check this:

if(entry.getFileName().endsWith(".java"))
Mukit09
  • 2,956
  • 3
  • 24
  • 44