所有Java對文件的處理類,Groovy都可以使用澎嚣。Groovy擴展了很多更加快捷和強大的方法疏尿。
讀取文件內(nèi)容的三種方式
第一種方式:
def file = new File("../../HelloGroovy.iml")
file.eachLine {line ->
println line
}
第二種方式:
println file.getText()
第三種方式:(返回的是一個集合)
println file.readLines()
讀取文件部分內(nèi)容:
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")
喜歡本篇博客的簡友們,就請來一波點贊易桃,您的每一次關(guān)注褥琐,將成為我前進的動力,謝謝晤郑!