-4

Why I couldn't print any word from these code? Eclipse didn't show any thing on Console field.

package test;

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;

public class Test2 {

    public static void main(String[] args) {
        PathMatcher matcher =
                FileSystems.getDefault().getPathMatcher("glob:*.{java,class}");

            Path filename = Paths.get("C:\\Users\\user\\eclipse-workspace\\test\\bin\\test");
            if (matcher.matches(filename)) {
                System.out.println(filename);
            }

    }   
}
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Squall Huang
  • 647
  • 9
  • 20
  • 2
    because the `matcher` does not match!? – luk2302 Jul 14 '18 at 09:56
  • 1
    Why should it print something? The path name does not match `*.java` or `*.class`. --- Are you under the mistaken assumption that any of that code would actually scan for files on your harddisk? If so, why do you believe so? – Andreas Jul 14 '18 at 09:59
  • But I have a lot of *.class file in "C:\\Users\\user\\eclipse-workspace\\test\\bin\\test" – Squall Huang Jul 14 '18 at 09:59
  • @SquallHuang Which part of your code do you believe will actually scan for files on your harddisk? Why do you believe so? Did you **read the javadoc** of the methods you're using? Which one would scan for files? – Andreas Jul 14 '18 at 10:01

1 Answers1

0

You are matching the directory path, not the files. If you want to match for a single file path you can do it like:

PathMatcher matcher = FileSystems.getDefault()
        .getPathMatcher("glob:**/*.{java,class}");
Path path = Paths.get("..", "classes", "MyClass.class");
if (matcher.matches(path)) {
  System.out.println(path);
}

Take a look at this answer which shows how to use the matcher with Files.walkFileTree() to check directories. It'd more or less the following:

PathMatcher matcher = FileSystems.getDefault()
        .getPathMatcher("glob:**/*.{java,class}");
Path path = Paths.get("..", "classes");
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        if (matcher.matches(file)) {
            System.out.println(file);
        }
        return FileVisitResult.CONTINUE;
    }
    ...
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • Thank you Karol. I have understood the method of "match for a single file path". But I don't understand how to use Files.walkFileTree(). I would like to print all *.class file in "C:\\Users\\user\\eclipse-workspace\\test\\bin\\test" directory on Console of Eclipse. – Squall Huang Jul 15 '18 at 10:52