Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 views
in Technique[技术] by (71.8m points)

how to replace a string/word in a text file in groovy

Hello I am using groovy 2.1.5 and I have to write a code which show the contens/files of a directory with a given path then it makes a backup of the file and replace a word/string from the file. here is the code I have used to try to replace a word in the file selected

String contents = new File( '/geretd/resume.txt' ).getText( 'UTF-8' ) 
contents = contents.replaceAll( 'visa', 'viva' )

also here is my complete code if anyone would like to modify it in a more efficient way, I will appreciate it since I am learning.

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' )
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As an alternative to loading the whole file into memory, you could do each line in turn

new File( 'destination.txt' ).withWriter { w ->
  new File( 'source.txt' ).eachLine { line ->
    w << line.replaceAll( 'World', 'World!!!' ) + System.getProperty("line.separator")
  }
}

Of course this (and dmahapatro's answer) rely on the words you are replacing not spanning across lines


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...