Curious
Curious

Reputation: 921

java stream filter not showing output

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

Upvotes: 1

Views: 537

Answers (1)

Derlin
Derlin

Reputation: 9881

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.

Upvotes: 4

Related Questions