控制台程序,列出目录的全部内容并使用过滤器来选择特定的条目。
import java.nio.file.*;
import java.io.IOException; public class ListDirectoryContents {
public static void main (String[] args) {
Path currentPath=Paths.get(System.getProperty("user.dir"));
currentPath=currentPath.getParent(); filterDirectoryContents(currentPath,null); System.out.println("\nFilter for .txt:");
filterDirectoryContents(currentPath,"*.txt"); System.out.println("\nFilter for .j???:");
filterDirectoryContents(currentPath,"*.j???");
} private static void filterDirectoryContents(Path path,String filter) {
try(DirectoryStream<Path> paths=filter != null ? Files.newDirectoryStream(path,filter) : Files.newDirectoryStream(path)){
System.out.println("\n" + path + " directory contains:");
for(Path p :paths){
System.out.println(" " + p.getFileName() + (Files.isDirectory(p) ? " is a directory." : ""));
}
}catch (NotDirectoryException e) {
System.err.println("Path is not a directory." + e);
}catch(IOException e) {
System.err.println("I/O error." + e);
}
}
}