您好我正在使用groovy 2.1.5并且我必须编写一个代码,该代码显示具有给定路径的目录的contens /文件,然后它对文件进行备份并从文件中替换单词/字符串.这是我用来尝试替换所选文件中的单词的代码
String contents = new File( '/geretd/resume.txt' ).getText( 'UTF-8' )
contents = contents.replaceAll( 'visa', 'viva' )
Run Code Online (Sandbox Code Playgroud)
这里也是我的完整代码,如果有人想以更有效的方式修改它,我会欣赏它,因为我正在学习.
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' )
Run Code Online (Sandbox Code Playgroud)
tim*_*tes 33
作为将整个文件加载到内存中的替代方法,您可以依次执行每一行
new File( 'destination.txt' ).withWriter { w ->
new File( 'source.txt' ).eachLine { line ->
w << line.replaceAll( 'World', 'World!!!' ) + System.getProperty("line.separator")
}
}
Run Code Online (Sandbox Code Playgroud)
当然这(和dmahapatro的答案)依赖于你正在替换的单词而不是跨行
Mic*_*ing 26
与几乎所有Groovy一样,AntBuilder是最简单的路径:
ant.replace(file: "myFile", token: "NEEDLE", value: "replacement")
Run Code Online (Sandbox Code Playgroud)
小智 13
我使用此代码直接在某些文件中将端口8080替换为$ {port.http}:
def file = new File('deploy/tomcat/conf/server.xml')
def newConfig = file.text.replace('8080', '${port.http}')
file.text = newConfig
Run Code Online (Sandbox Code Playgroud)
第一个字符串将文件的一行读入变量.第二个字符串执行替换.第三个字符串将变量写入文件.
请参阅此答案,更换图案.可以使用相同的原理来替换字符串.
样品
def copyAndReplaceText(source, dest, Closure replaceText){
dest.write(replaceText(source.text))
}
def source = new File('source.txt') //Hello World
def dest = new File('dest.txt') //blank
copyAndReplaceText(source, dest) {
it.replaceAll('World', 'World!!!!!')
}
assert 'Hello World' == source.text
assert 'Hello World!!!!!' == dest.text
Run Code Online (Sandbox Code Playgroud)
小智 5
使用“文件”对象的答案是好的且快速的,但是通常会导致以下错误,当然可以避免,但是以失去安全性为代价:
不允许脚本使用新的java.io.File java.lang.String。管理员可以决定是批准还是拒绝此签名。
此解决方案避免了上面提出的所有问题:
String filenew = readFile('dir/myfile.yml').replaceAll('xxx','YYY')
writeFile file:'dir/myfile2.yml', text: filenew
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79736 次 |
| 最近记录: |