Skip to content

Instantly share code, notes, and snippets.

@sanaulla123
Created July 19, 2012 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanaulla123/3145846 to your computer and use it in GitHub Desktop.
Save sanaulla123/3145846 to your computer and use it in GitHub Desktop.
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