Grale系列八之文件处理

所有Java对文件的处理类,Groovy都可以使用。Groovy扩展了很多更加快捷和强大的方法。

读取文件内容的三种方式

第一种方式:

def file = new File("../../HelloGroovy.iml")
file.eachLine {line ->
    println line
}

第二种方式:

println file.getText()

第三种方式:(返回的是一个集合)

println file.readLines()
读取文件部分内容:
println file.withReader { reader ->
    def buffer = new char[100]
    reader.read(buffer)
    return buffer
}
拷贝文件
def copy(String sourceFilePath, String destFilePath) {
    try {
        def destFile = new File(destFilePath)
        if (!destFile.exists()) {
            destFile.createNewFile()
        }

        def sourceFile = new File(sourceFilePath)
        if (!sourceFile.exists()) {
            throw new Exception("source file is not exists!!")
        }

        sourceFile.withReader { reader ->
            def lines = reader.readLines()
            destFile.withWriter { write ->
                lines.each { line ->
                    write.append(line + "\r\n")
                }
            }
        }
        return true
    } catch (Exception e) {
        e.printStackTrace()
    }
}

println copy("../../HelloGroovy.iml", "../HelloGroovy2.iml")

或者简单点:

def copy(String sourceFilePath, String destFilePath) {
    try {
        def destFile = new File(destFilePath)
        if (!destFile.exists()) {
            destFile.createNewFile()
        }

        def sourceFile = new File(sourceFilePath)
        if (!sourceFile.exists()) {
            throw new Exception("source file is not exists!!")
        }
        
        def text = sourceFile.getText()
        destFile.setText(text)
        return true
    } catch (Exception e) {
        e.printStackTrace()
    }
}

println copy("../../HelloGroovy.iml", "../HelloGroovy2.iml")

喜欢本篇博客的简友们,就请来一波点赞,您的每一次关注,将成为我前进的动力,谢谢!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,144评论 1 32
  • feisky云计算、虚拟化与Linux技术笔记posts - 1014, comments - 298, trac...
    不排版阅读 3,923评论 0 5
  • 本篇主要是个人学习gradle的笔记总结 一.开始之前 1. 为什么学习Gradle 采用DSL(Doma...
    zyq_neuq阅读 1,539评论 2 12
  • Groovy :是一种动态语言。 1:这种语言比较有特点,它和 Java 一样,也运行于 Java 虚拟机中。简单...
    PeytonWu阅读 1,603评论 0 1
  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,820评论 0 10