Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Listing and filtering directory content
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DirectoryFilterTest {
public static void main(String[] args) {
Path basePath = Paths.get("D:/tests");
// Listing the files in the directory
System.out.println("All files:");
try (DirectoryStream<Path> pathList = Files.newDirectoryStream(basePath)) {
for (Path path : pathList) {
System.out.println(path.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
// Applying filter using GLOB pattern
System.out.println("All text files[Using Glob pattern]:");
try (DirectoryStream<Path> pathList = Files.newDirectoryStream(basePath,
"*.txt")) {
for (Path path : pathList) {
System.out.println(path.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
// Using DirectoryStream.Filter class
System.out.println("All document files[Using Filter class]");
DirectoryStream.Filter<Path> documentFilter = new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
String fileName = entry.getFileName().toString();
return fileName != null && fileName.endsWith("txt");
}
};
try (DirectoryStream<Path> pathList = Files.newDirectoryStream(basePath,
documentFilter)) {
for (Path path : pathList) {
System.out.println(path.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.