public
Created

Listing and filtering directory content

  • Download Gist
DirectoryFilterTest.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
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();
}
 
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.