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 就没有这个问题。

发布了156 篇原创文章 · 获赞 19 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/qq_36929361/article/details/104246976