groovy文件操作工具类

class FileUtils{


    /**
     * remove the target file or directory.
     * @param src the full path of the target file
     * @return true if the file or directory is successfully removed; false otherwise.
     */
    static void rm(String src) {
        rm(src, null);
    }

    static void rmBySuffix(String path, String suffix) {
        rm(path, { it.endsWith(suffix) })
    }


    static def rm(String src, Closure filter) {
        iterator(src, filter, { path -> rm(path, filter) }, { file -> file.delete() });
    }

    static def cp(String src, String dsc) {
        def srcFile = new File(src);
        assert src != dsc;
        assert new File(srcFile).exists();
        new File(dsc).setBytes(srcFile.getBytes());
    }

    static def mv(String from, String to) {
        cp(from, to);
        rm(from);
    }

    static def mergeTo(String from, def to, Closure filter) {
        def toFile = to;
        if (to instanceof String) {
            toFile = new File(to);
        }
        iterator(from, filter, { mergeTo(it, toFile, filter) }, { toFile.append(it.getBytes()) });
    }

    private static void iterator(String src, Closure filter, Closure directoryAction, Closure fileAction) {
        def file = new File(src);
        assert file.exists();
        if (file.isDirectory()) {
            file.eachFile {
                directoryAction.call(it.getAbsolutePath());
            }
        }
        if ((!filter) || filter.call(src)) {
            fileAction.call(file);
        }
    }
}
def src = "c:/test.txt";
def dsc = "d:/test.txt";
//FileUtils.cp(src, dsc)
//FileUtils.rmBySuffix("E:/workspace/groovy/src", "class")
//FileUtils.mergeTo("c:/test/cc.txt", "d:/result.txt",{String path->path.endsWith("txt")});
//FileUtils.mergeTo("c:/test", "d:/result.txt",{String path->path.endsWith("txt")});
Utils.rmBySuffix("E:/workspace/groovy/src","class")

       作为脚本语言,groovy对java的文件操作进行了扩展,利用这些扩展与脚本语言的灵活性,可以很方便的帮助我们快速编写工作脚本与批处理脚本。

猜你喜欢

转载自wolfcame.iteye.com/blog/2328072