第五章 gradle自动化构建系列文章 之 Groovy基础语法 - 文件处理
<、center>
查看 “Android自动化构建系列” 全部文章
1. 纯文本文件 通过file.eachLine() 方法 逐行 读取
File file= new File('../../langs.xml')
file.eachLine {line->
println line
}
-
运行结果:
2. 纯文本文件 通过file.getText() 方法 一次性读取全部内容,并以String类型返回
def text= file.getText()
println text
-
运行结果:
3. 纯文本文件 通过file.readLines() 方法 一次性读取全部内容,并以ArrayList类型返回
def resultList = file.readLines()
println resultList.toListString()
-
运行结果:
4. 普通文件 通过file.withReader() 方法 读取部分内容,并以期望的类型返回,通常为String
//读取普通文件(包括非文本文件)的部分内容
def reader = file.withReader { reader ->
char[] buffer = new char[100]
reader.read(buffer)
return buffer
}
println reader
-
运行结果:
5. 读写实践案例 ,将一个文件复制到另一个文件
//文件拷贝实践,将一个文件拷贝到另一个文件
copy('../../langs.xml','../../langsCopy.xml')
def copy(String sourcePath, String destationPath) {
//判断目标文件不存在,创建文件
File destFile = new File(destationPath)
try {
if (!destFile.exists()) {
destFile.createNewFile()
}
} catch (Exception e) {
e.printStackTrace()
}
File sourceFile = new File(sourcePath)
try {
if (!sourceFile.exists()) {
return
}
} catch (Exception e) {
e.printStackTrace()
return
}
def lines = sourceFile.readLines()
destFile.withWriter {writer->
lines.each {line->
writer.append(line).append('\r\n')
}
}
}
-
运行结果:
6. groovy中的序列化对象读、写
-
向文件中存入一个对象(对象必须实现 Serializable)
//对象存储 def saveObject(Object o, String path) { //判断目标文件不存在,创建文件 File destFile = new File(path) try { if (!destFile.exists()) { destFile.createNewFile() } } catch (Exception e) { e.printStackTrace() } if (o == null) { return } try { destFile.withObjectOutputStream { outputStream -> outputStream.writeObject(o) } } catch (Exception e) { e.printStackTrace() } } saveObject(animal, "../../langsSave.xml")
-
从文件中读取存储的对象实例
def readObject(String path) { //判断目标文件不存在,创建文件 File destFile = new File(path) try { if (!destFile.exists()) { return null } } catch (Exception e) { e.printStackTrace() return null } try { destFile.withObjectInputStream { inputStream -> return inputStream.readObject() } } catch (Exception e) { e.printStackTrace() return null } } def readA =(Animal) readObject("../../langsSave.xml") println "Animal's name is ${readA.name},Animal's age is ${readA.age}"
-
运行结果: