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的文件操作进行了扩展,利用这些扩展与脚本语言的灵活性,可以很方便的帮助我们快速编写工作脚本与批处理脚本。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值