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' )
replaceAll() is a function in groovy that replaces all occurrences of a string with a specified string.
Open the text file in Notepad. Click Edit on the menu bar, then select Replace in the Edit menu. Once in the Search and Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options section for further information and help.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With