Groovy操作复制文件

Groovy操作复制文件

虽然Groovy最后的实现逻辑也是Java的那一套,但是其简介的语法真的是让人欲罢不能

复制文本

def copy(String srcPath, String destPath) {
    def f = new File(srcPath)
    def d = new File(destPath)

    if (!d.exists()) {
        d.createNewFile()
    }

    f.withReader {
        reader ->
            def lines = reader.readLines()

            d.withWriter { writer ->
                lines.each {
                    writer.append(it + "\r\n")
                }
            }

    }
    return true
}

assert copy("../hello_groovy.iml", "../hello_groovy2.iml")

在Groovy中,调用with系列处理文件是不用关流的,Groovy已经帮我们做好了。

复制文件

如下方法是把系统里面某个文件夹下面的所有jpg数据都copy到指定的一个文件夹中

def copy(String src, String dest) {
    def f = new File(src)
    def list = f.list(new FilenameFilter() {
        @Override
        boolean accept(File dir, String name) {
            return name.endsWith("jpg")
        }
    })

    def desk = new File(dest)
    if (!desk.exists()) {
        desk.mkdirs()
    }

    list.each {
        File f1 = new File(src + "/" + it)
        File f2 = new File(dest + "/" + it)

        if (!f2.exists()) {
            f2.createNewFile()
        }
        f1.withDataInputStream {
            input ->
                f2.withDataOutputStream {
                    output -> output << input
                }
        }
    }
    return true
}

assert copy("F:/photo","../photo")

简单说一句,我使用withInputStream最终copy出来的文件打不开,但是使用withDataInputStream 就没有这个问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员大航子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值