def file = new File('t.iml')
file.eachLine {
line -> println line
}
println "--------------------1--------------------------"
def text = file.getText()
println text
println "--------------------2--------------------------"
def result = file.readLines()
result.each { println it.toString()}
println "---------------------3--------------------------"
//读取文件部分内容
def reader = file.withReader { reader ->
char[] buffer = new char[100]
reader.read(buffer)
return buffer
}
println reader //只输出前100个字符
文件的复制
def rs = copy('t.iml', 't2.iml')
def copy(String sourcePath, String targetPath) {
try {
//首先创建目标文件
def targetFile = new File(targetPath)
if (!targetFile.exists()) {
targetFile.createNewFile()
}
//开始copy
new File(sourcePath).withReader { read ->
def lines = read.readLines()
targetFile.withWriter { writer ->
lines.each { line ->
writer.append(line).append("\n")
}
}
}
return true
} catch (Exception e) {
}
}
文件的读写
println saveObject(new LawCase(id: "199", name: "jimmy"), "case.bin")
//对象的读写
def saveObject(Object obj, String targetPath) {
try {
//首先创建目标文件
def targetFile = new File(targetPath)
if (!targetFile.exists()) {
targetFile.createNewFile()
}
targetFile.withObjectOutputStream { out ->
out.writeObject(obj)
}
return true;
} catch (Exception e) {
}
return false
}
println readObject("case.bin")
static 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()
}
} catch (Exception e) {
}
return obj
}
网友评论