[Java] 多重目录下的文件打印--摘自Java编程思想 →→→→→进入此内容的聊天室

来自 , 2020-06-11, 写在 Java, 查看 119 次.
URL http://www.code666.cn/view/3e15cc11
  1. /**
  2.  * 目录实用工具  策略设计模式  目录下的文件
  3.  * @author LHL
  4.  *
  5.  */
  6. public class ProcessFiles {
  7.         public interface Strategy{
  8.                 void process(File file);
  9.         }
  10.         private Strategy strategy;
  11.         private String ext;
  12.         public ProcessFiles(Strategy strategy,String ext) {//有参构造器
  13.                 this.strategy = strategy;
  14.                 this.ext = ext;
  15.         }
  16.         public void start(String[] args) {
  17.                 try {
  18.                         if(args.length == 0) {
  19.                                 processDirectoryTree(new File("."));//目录
  20.                         }else {
  21.                                 for(String arg : args) {
  22.                                         File fileArg = new File(arg);
  23.                                         if(fileArg.isDirectory()) {//判断是否是目录
  24.                                                 processDirectoryTree(fileArg);
  25.                                         }else {
  26.                                                 if(!arg.endsWith("."+ext)) {//后缀
  27.                                                         arg += "."+ext;//后缀拼接
  28.                                                 }
  29.                                                 strategy.process(new File(arg).getCanonicalFile());//该方法返回同一个文件或目录的规范路径名字符串表示
  30.                                         }
  31.                                 }
  32.                         }
  33.                 } catch (IOException e) {
  34.                         // TODO: handle exception
  35.                         throw new RuntimeException(e);
  36.                 }
  37.         }
  38.        
  39.         private void processDirectoryTree(File root) throws IOException {//返回目录下的文件
  40.                 // TODO Auto-generated method stub
  41.                 for(File file : Directory.TreeInfo.walk(root.getAbsolutePath(),".*\\."+ext)) {
  42.                         strategy.process(file.getCanonicalFile());
  43.                         //System.out.println(file);
  44.                 }
  45.         }
  46.         public static void main(String[] args) {
  47.                 // TODO Auto-generated method stub
  48.                 String suffix = "class";//后缀名
  49.                 new ProcessFiles(new Strategy() {//通过有参构造器创建ProcessFiles对象(参数Strategy,String)
  50.                         @Override
  51.                         public void process(File file) {
  52.                                 // TODO Auto-generated method stub
  53.                                 System.out.println(file);
  54.                         }
  55.                 }, suffix).start(args);//给构造器传参
  56.         }
  57. }

回复 "多重目录下的文件打印--摘自Java编程思想"

这儿你可以回复上面这条便签

captcha