Java基础之访问文件与目录——列出目录内容(ListDirectoryContents)

控制台程序,列出目录的全部内容并使用过滤器来选择特定的条目。

 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);
}
}
}
上一篇:关于hadoop学习的思考(一) —— 小的知识点的总结


下一篇:easyUI之datagrid绑定后端返回数据的两种方式