Gradle技术之二 Groovy对文件的操作

827 阅读2分钟

Groovy对文件的操作

对文件的遍历 假设文件的原始内容为:

hello,world
这里是北京
andorid and ios are good system

第一种方法:使用 eachLine()

//1.1 new 一个File
def file = new File(filepath)

//1.2 groovy对文件的遍历
file.eachLine {
    //打印每一行内容
    line -> println line
}

//输出
hello,world
这里是北京
andorid and ios are good system

第二种方法:使用File的getText()

def content = file.getText()
println content
//输出
hello,world
这里是北京
andorid and ios are good system

是不是更简单,直接调用一个方法就OK了,比Java操作文件要简单太多了吧

第三种方法:使用 file.readLines()方法

def list = file.readLines()
list.collect {
    println it
}

println "文件有" + list.size() + "行"
//输出
hello,world
这里是北京
andorid and ios are good system
文件有3

是不是很方便,readLines()函数直接把文件内容以行为单位读取到一个List中,这样操作就更方便了

第四种方法:读取文件部分内容

//读取前20个字符
def reader = file.withReader {
    reader ->
        char[] buffer = new char[20]
        reader.read(buffer)
        return buffer
}

println reader
//输出
hello,world
这里是北京
an

如何拷贝文件?

我们写一个方法,把刚才的文件拷贝到另一个文件中去,代码如下:

def copy(String sourcePath, String destPath) {
    try {
        //1 创建目标文件
        def destFile = new File(destPath)
        if (!destFile.exists()) {
            destFile.createNewFile()
        }

        //2 开始拷贝
        new File(sourcePath).withReader { reader ->
            def lines = reader.readLines()
            destFile.withWriter { writer ->
                lines.each {
                    //把每一行都写入到目标文件中
                    line -> writer.append(line+"\r\n")
                }
            }
        }

        return true
    } catch (Exception e) {
        return false
    }
}

读写对象 有时候我们会有这样的需求,需要把我们的bean对象写入到文件中,用到的时候再读出来,下面我们就来实现这样的功能,代码如下:

//将一个对象写入到文件中
def saveObject(Object object, String path) {
    try {
        //1 首先创建目标文件
        def destFile = new File(path)
        if (!destFile.exists()) {
            destFile.createNewFile()
        }

        destFile.withObjectOutputStream { out ->
            out.writeObject(object)
        }

        return true
    } catch (Exception e) {
    }

    return false;
}

//从一个文件中读到bean
def readObject(String path) {
    def obj = null
    try {
        //1 先判断文件是否存在
        def file = new File(path)
        if (!file.exists()) {
            return null
        }

        //2 从文件中读取对象
        file.withObjectInputStream { reader ->
            obj = reader.readObject();
        }

        return obj
    } catch (Exception e) {
    }

    return null
}

Groovy对xml文件的操作

/**
     test.xml 文件的内容如下:

     <langs type="current">
         <language1>Java</language1>
         <language2>Groovy</language2>
         <language3>JavaScript</language3>
     </langs>
 */

//一行代码就解析了xml
def langs = new XmlParser().parse("test.xml")

//打印出node的属性
println langs.attribute('type')

//对xml文件的遍历
langs.each {
    println it.text()
}

//输出
current
Java
Groovy
JavaScript

以上就是groovy对文件的操作