Reputation: 2123
I want to list out only file names from the folder in Java 8 ending with .txt
extension.
With this piece of code I got all the files names, and there are a lot with .txt extensions:
List<Path> fileNames = Files.list(configFilePath)
.map(Path::getFileName)
.sorted()
.collect(toList());
But with this code I get an empty:
List<Path> fileNames = Files.list(configFilePath)
filter(file -> file.getFileName().endsWith(".txt"))
.map(Path::getFileName)
.sorted()
.collect(toList());
Upvotes: 4
Views: 9579
Reputation: 138824
To achieve this, please use the following line of code:
Files.list(configFilePath)
.filter(s -> s.toString().endsWith(".txt"))
.forEach(System.out::println);
Your task was to get only file names from the folder which are ending with .txt
. So the simplest way to achieve this is to use filter
method which takes as an argument a predicate. Using a predicate it means that is keeps all the elements that satisfy the given condition. Because you have a List
of Path
objects we first need to convert those objects to String and check if it ends with .txt
. Finally we just print the result.
Upvotes: 9