标签:
今天闲来无事,自己实现了一个打印文件和展示文件目录的小功能;输入文件或目录,若为文件打印其路径和名字,若为目录,可选文件后缀名,若不选,则打印其下所有文件,若选择后缀名,则打印其下所有匹配后缀名的文件。代码如下:
/* * 输入文件或目录,若为文件打印其路径和名字, * 若为目录,可选文件后缀名,若不选,则打印其下所有文件, * 若选择后缀名,则打印其下所有匹配后缀名的文件 * * * mist lee,2014-11-29*/ import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.Scanner; public class DisplayFileState { private static boolean flag = false; public static void main(String[] args) throws IOException { //String fileName = rawInput(); Scanner in = new Scanner(System.in); System.out.print("请输入文件或者目录路径:"); String fileName = in.nextLine(); File f = new File(fileName); if(f.isFile()) { System.out.println("所输入的路径是文件"); System.out.println(f.getCanonicalPath()); } else if(f.isDirectory()) { System.out.println("所输入的路径是目录"); System.out.println("请输入要查找文件的后缀名,若为空则显示所有文件"); String ext = in.nextLine(); System.out.println("您要查找的文件的后缀名是:" + ext); spreadFileDir(f,ext); } else { System.out.println("输入有误,请确认后重新输入!"); } if(flag) System.out.println("没能找到你所需要的文件"); } //展开目录文件 private static void spreadFileDir(File f, String ext) throws IOException { String[] fileNames = f.list(); //boolean flag = false; for(int i=0;i<fileNames.length;i++) { File subFile = new File(f.getPath(),fileNames[i]); if(subFile.isFile()) { if(ext.equals(" ")) System.out.println(subFile.getCanonicalPath()); else { ExtensionFilter extFilter = new ExtensionFilter(ext); boolean isTrue = extFilter.accept(f, fileNames[i]); if(isTrue) System.out.println(subFile.getCanonicalPath()); else flag = true; //flag = isTrue^false; } } else if(subFile.isDirectory()) { spreadFileDir(subFile,ext); } else { System.out.println("something is worong!"); } } } } //辅助过滤类,用以处理文件的后缀名 class ExtensionFilter implements FilenameFilter { public ExtensionFilter(String ext) { extension = "." + ext; } @Override public boolean accept(File dir, String name) { // TODO Auto-generated method stub return name.endsWith(extension); } private String extension; }
标签:
原文地址:http://www.cnblogs.com/mist-lee/p/4784152.html