/** * 目录实用工具 策略设计模式 目录下的文件 * @author LHL * */ public class ProcessFiles { public interface Strategy{ void process(File file); } private Strategy strategy; private String ext; public ProcessFiles(Strategy strategy,String ext) {//有参构造器 this.strategy = strategy; this.ext = ext; } public void start(String[] args) { try { if(args.length == 0) { processDirectoryTree(new File("."));//目录 }else { for(String arg : args) { File fileArg = new File(arg); if(fileArg.isDirectory()) {//判断是否是目录 processDirectoryTree(fileArg); }else { if(!arg.endsWith("."+ext)) {//后缀 arg += "."+ext;//后缀拼接 } strategy.process(new File(arg).getCanonicalFile());//该方法返回同一个文件或目录的规范路径名字符串表示 } } } } catch (IOException e) { // TODO: handle exception throw new RuntimeException(e); } } private void processDirectoryTree(File root) throws IOException {//返回目录下的文件 // TODO Auto-generated method stub for(File file : Directory.TreeInfo.walk(root.getAbsolutePath(),".*\\."+ext)) { strategy.process(file.getCanonicalFile()); //System.out.println(file); } } public static void main(String[] args) { // TODO Auto-generated method stub String suffix = "class";//后缀名 new ProcessFiles(new Strategy() {//通过有参构造器创建ProcessFiles对象(参数Strategy,String) @Override public void process(File file) { // TODO Auto-generated method stub System.out.println(file); } }, suffix).start(args);//给构造器传参 } }