所有Java对文件的处理类,Groovy都可以使用。Groovy扩展了很多更加快捷和强大的方法。
读取文件内容的三种方式
第一种方式:
def file = new File("../../HelloGroovy.iml")
file.eachLine {line ->
println line
}
第二种方式:
println file.getText()
第三种方式:(返回的是一个集合)
println file.readLines()
读取文件部分内容:
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")
喜欢本篇博客的简友们,就请来一波点赞,您的每一次关注,将成为我前进的动力,谢谢!