Sometimes we might need files with a particular extension. We will see how to get a file with a particular extension in Java 8.
Say there are various files extensions like .pdf, .doc, .txt, etc. Suppose we need files only in .txt extension we will use Java NIO Path API to get files ending with a specific extension. Path endsWith method is used to get the specific extension. Path interface is introduced in Java 7.
Path get method converts the path string to Path.
Filter the file with .txt extension and collect the Files as a List.
private static List<File> getFilesWithSpecificExtension(final String directoryPath) throws IOException {
try (final Stream<Path> fileStream = Files.list(Paths.get(directoryPath))) {
return fileStream
.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(".txt"))
.map(Path::toFile)
.collect(Collectors.toList());
}
Output
This program list the files in .txt extension with in a folder.
F:\Files\New Text Document.txt
F:\Files\Spring Boot Tutorial.txt
F:\Files\Topics to Cover.txt
Directly return List of File instead of assigning to Stream of Path.
private static List<File> getFilesWithSpecificExtension(final String directoryPath) throws IOException {
return Files.list(Paths.get(directoryPath))
.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(".txt"))
.map(Path::toFile)
.collect(Collectors.toList());
}
Java 8 Files.walk
In Java 8 we are having Files.walk to walk a File tree. Filter the file by a certain extension and return the List of Files.
Here we returned only FileName instead of the whole path.
private static List<File> getFilesWithSpecificExtension(final String directoryPath) throws IOException {
try (final Stream<Path> fileStream = Files.walk(Paths.get(directoryPath))) {
return fileStream
.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(".txt"))
.map(Path::getFileName)
.map(Path::toFile)
.collect(Collectors.toList());
}
}
Output
New Text Document.txt
Spring Boot Tutorial.txt
Topics to Cover.txt
Main class
package com.digitizedpost.files;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FileExtension {
public static void main(String[] args) {
try {
getFilesWithSpecificExtension("F:\\Files").forEach(e -> System.out.println(e));
} catch (IOException e) {
e.printStackTrace();
}
}
//getFilesWithSpecificExtension1 method
}