编程语言
首页 > 编程语言> > Java编程思想:File类getCanonicalFile()方法,listFile()方法

Java编程思想:File类getCanonicalFile()方法,listFile()方法

作者:互联网

import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import java.io.File;
import java.io.FilenameFilter;

public class Test {
    public static void main(String[] args) {
//        DirectoryDemo.test();
        ProcessFileTest.test();
        ProcessFileTest.test2();

    }
}

/*
    local():产生由本地目录中的文件构成的File对象数组
    walk():产生给定目录下的由整个目录书中所有文件构成的List<File>
 */

class Directory {
    public static File[] local(File dir, String regex) {
        return dir.listFiles(new FilenameFilter() {
            Pattern pattern = Pattern.compile(regex);
            @Override
            public boolean accept(File dir, String name) {
                return pattern.matcher(name).matches();
            }
        });
    }

    public static class TreeInfo implements Iterable<File>{

        public List<File> dirs = new ArrayList<>();
        public List<File> files = new ArrayList<>();

        public TreeInfo() {

        }

        public void addAll(TreeInfo infos) {
            this.dirs.addAll(infos.dirs);
            this.files.addAll(infos.files);
        }

        @Override
        public Iterator<File> iterator() {
            return files.iterator();
        }

        public String toString() {
            return "dirs: " + PPrint.pformat(dirs) + "\n\nfiles:" + PPrint.pformat(files);
        }
    }


    public static File[] local(String path, String regex) {
        return local(new File(path),regex);
    }

    private static TreeInfo recurseDirs(File startDir, String regex) {
        TreeInfo result = new TreeInfo();
        for (File item : startDir.listFiles()) {
            if (item.isDirectory()) {
                result.dirs.add(item);
                result.addAll(recurseDirs(item,regex));
            } else {
                //这个地方的写法和我之前看到的不太一样
                if (item.getName().matches(regex)) {
                    result.files.add(item);
                }
            }
        }
        return result;
    }

    public static TreeInfo walk(String start, String regex) {
        return recurseDirs(new File(start),regex);
    }

    public static TreeInfo walk(File start, String regex) {
        return recurseDirs(start, regex);
    }

    public static TreeInfo walk(String start) {
        return recurseDirs(new File(start), ".*");
    }
}

class PPrint {
    public static String pformat(Collection<?> collection) {
        if (collection.size() == 0) {
            return "[]";
        }

        StringBuilder result = new StringBuilder("[");
        for (Object elem : collection) {
            if (collection.size() != 1) {
                result.append("\n   ");
            }
            result.append(elem);
        }
        if (collection.size() != 1) {
            result.append("\n");
        }
        result.append("]");
        return  result.toString();

    }

    public static void pprint(Collection<?> c) {
        System.out.println(pformat(c));
    }

    public static void pprint(Object[] objects) {
        System.out.println(pformat(Arrays.asList(objects)));
    }
}

class DirectoryDemo {
    public static void test() {
        PPrint.pprint(Directory.walk(".").dirs);
    }
}

/*
    创建一个工具,它可以在目录中穿行,并且根据Strategy对象来处理这些目录中的文件

    书中案例的逻辑:
        1.针对上一个案例中walk方法计算出来的所有文件,执行一个策略方法


 */

//书中原代码:
/*
    ProcessFiles的工作是:执行查找具有特定扩展名的文件的所有工作
    Strategy的工作是:查找到指定的文件后,执行某个指定的算法
 */
class ProcessFiles {
    public interface Strategy {
        void process(File file);
    }

    private Strategy strategy;
    private String ext;

    public ProcessFiles(Strategy s,String ext){
        this.strategy=s;
        this.ext=ext;
    }

    public void processDirectoryTree(File root) throws IOException {
        for (File file : Directory.walk(root.getAbsolutePath(), ".*\\." + ext)) {
            strategy.process(file.getCanonicalFile());
        }
    }

    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) {
            e.printStackTrace();
        }
    }
}

//改进后代码
interface IStrategy{
    void process(File file);
}

class ProcessFiles1 {
    private IStrategy strategy;
    private String ext;

    public ProcessFiles1(IStrategy strategy, String ext) {
        this.strategy=strategy;
        this.ext=ext;
    }


    public void start(String[] paths){
        for(String path:paths){
            start(path);
        }
    }

    public void start(String path) {
        core(new File(path));
    }

    public void start(){
        start(".");
    }

    private void core(File root){
        if(root.isFile()){
            strategy.process(root);
            return;
        }
        for (File item : Directory.walk(root.getAbsolutePath(), ".*\\." + ext)) {
            strategy.process(root);
        }
        return;
    }

}

class ProcessFileTest {
    public static void test() {

        new ProcessFiles(new ProcessFiles.Strategy(){
            public void process(File file) {
                System.out.println(file);
            }
        },"java").start(new String[0]);

    }

    public static void test2() {
        new ProcessFiles1(new IStrategy(){
            public void process(File file) {
                try {
                    System.out.println(file.getCanonicalFile());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        },"java").start();
    }
}

 

标签:getCanonicalFile,Java,String,void,listFile,static,File,new,public
来源: https://www.cnblogs.com/junjie2019/p/10537995.html