我是靠谱客的博主 兴奋大神,这篇文章主要介绍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 + "rn")
                }
            }

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

最后

以上就是兴奋大神最近收集整理的关于Groovy操作复制文件的全部内容,更多相关Groovy操作复制文件内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部