加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何在groovy中替换文本文件中的字符串/单词

发布时间:2020-12-14 16:37:39 所属栏目:大数据 来源:网络整理
导读:您好,我使用的是groovy 2.1.5,我必须编写一个代码,显示具有给定路径的目录的contens /文件,然后它备份文件并从文件中替换一个单词/字符串。 这里是我用来尝试替换所选文件中的单词的代码 String contents = new File( '/geretd/resume.txt' ).getText( '
您好,我使用的是groovy 2.1.5,我必须编写一个代码,显示具有给定路径的目录的contens /文件,然后它备份文件并从文件中替换一个单词/字符串。
这里是我用来尝试替换所选文件中的单词的代码

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)依赖于你所替代的词,而不是跨线

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读