您好,我使用的是groovy 2.1.5,我必须编写代码以显示具有给定路径的目录的目录/文件,然后对文件进行备份并替换文件中的单词/字符串。
这是我用来尝试替换所选文件中的单词的代码
String contents = new File( '/geretd/resume.txt' ).getText( 'UTF-8' )
contents = contents.replaceAll( 'visa', 'viva' )
如果有人想以更有效的方式修改它,这也是我的完整代码,自从我学习以来,我将不胜感激。
def dir = new File('/geretd')
dir.eachFile {
if (it.isFile()) {
println it.canonicalPath
}
}
copy = { File src,File dest->
def input = src.newDataInputStream()
def output = dest.newDataOutputStream()
output << input
input.close()
output.close()
}
//File srcFile = new File(args[0])
//File destFile = new File(args[1])
File srcFile = new File('/geretd/resume.txt')
File destFile = new File('/geretd/resumebak.txt')
copy(srcFile,destFile)
x = " "
println x
def dire = new File('/geretd')
dir.eachFile {
if (it.isFile()) {
println it.canonicalPath
}
}
String contents = new File( '/geretd/resume.txt' ).getText( 'UTF-8' )
contents = contents.replaceAll( 'visa', 'viva' )
最佳答案
作为将整个文件加载到内存的替代方法,您可以依次执行每一行
new File( 'destination.txt' ).withWriter { w ->
new File( 'source.txt' ).eachLine { line ->
w << line.replaceAll( 'World', 'World!!!' ) + System.getProperty("line.separator")
}
}
当然,这个(和dmahapatro's answer)依赖于您要替换的单词而不是跨行的
关于groovy - 如何在Groovy中替换文本文件中的字符串/单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17395787/