1

The following code displays files.

Files.walk(Paths.get("E:\\pdf"))
                .map(path -> path.toAbsolutePath().getFileName())
                        .forEach(System.out::println);

But this dosen't display pdf output why it is not working ?

Files.walk(Paths.get("E:\\pdf"))
                .map(path -> path.toAbsolutePath().getFileName())
                    .filter(path -> path.endsWith(".pdf"))
                        .forEach(System.out::println);
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Curious
  • 921
  • 1
  • 9
  • 25

1 Answers1

4

As this question points out and this article explains, path.endsWith() only returns true if there is a complete match for everything after the final directory separator:

If you need to compare the java.io.file.Path object, be aware that Path.endsWith(String) will ONLY match another sub-element of Path object in your original path, not the path name string portion! If you want to match the string name portion, you would need to call the Path.toString() first.

A quick fix is to replace the filter with:

path.toString().toLowerCase().endsWith(".pdf");

There is also Java NIO's PathMatcher, which is made for dealing with paths. Here is an example:

final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.pdf");

You can use with:

.filter(path -> matcher.matches(path))

See Finding Files tutorial for more details.

Community
  • 1
  • 1
Derlin
  • 9,572
  • 2
  • 32
  • 53