版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huanghuangjin/article/details/82286858
file
def file = new File('../../hjGroovy.iml')
//file.eachLine { println it } // 读取文件每一行 , ResourceGroovyMethods 中提供的 方法
String content = file.getText() // 获取文件中所有字符
def list = file.readLines() // 读取文件每行,返回每行字符串的集合
def reader = file.withReader { // 获取Reader对象,进行文件操作
reader ->
char[] buf = new char[100]
reader.read(buf) // 读取文件中的前 100 个字符
return buf
}
//println reader // 打印
// 复制文本文件,二进制文件的复制? file.withDataInputStream {} ? file.withDataOutputStream {} ?
def copy(String srcPath, String dstPath) {
try {
def srcFile = new File(srcPath)
def dstFile = new File(dstPath)
if (!dstFile.exists()) dstFile.createNewFile()
srcFile.withReader { reader ->
def lines = reader.readLines()
dstFile.withWriter { writer -> // 获取Writer对象,可以对文件进行写的操作 , groovy会自动关闭流
lines.each { line ->
writer.append(line+'\r\n')
}
}
}
} catch (Exception e) { }
}
copy('E:\\gradle\\a.txt', 'E:\\gradle\\copy.txt')
// 序列化与反序列化
class ABC {
String name
int age
}
def saveObject(Object object, String path) {
try {
//首先创建目标文件
def desFile = new File(path)
if (!desFile.exists()) desFile.createNewFile()
desFile.withObjectOutputStream {
out -> out.writeObject(object)
}
} catch (Exception e) { }
}
def readObject(String path) {
def obj = null
try {
def file = new File(path)
if (file == null || !file.exists()) return null
//从文件中读取对象
file.withObjectInputStream {
input -> obj = input.readObject()
println obj==null
}
} catch (Exception e) { }
return obj
}
def po = new ABC(name: 'abc', age: 26)
saveObject(po, 'E:\\gradle\\abc.bin')
def ret = (ABC) readObject('E:\\gradle\\abc.bin')
println "name is ${ret.name}, age is ${ret.age}"