Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting only file names from the folder in Java8 with Filtering

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());
like image 884
en Lopes Avatar asked Jan 03 '23 03:01

en Lopes


1 Answers

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.

like image 127
Alex Mamo Avatar answered Jan 13 '23 12:01

Alex Mamo