Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using groovy to append to a certain line number in a file

Tags:

groovy

Rather than appending to the end of a file, I am trying to replace or append to a certain line using groovy File manipulation.

Is there a method to do this? append adds to end of file while write overwrites existing file:

def file = new File("newFilename")
file.append("I wish to append this to line 8")
like image 289
morrrowgi Avatar asked Dec 02 '25 22:12

morrrowgi


1 Answers

In general, with Java and Groovy file handling, you can only append to the end of files. There is no way to insert information, although you can overwrite data anywhere without shifting the position of what follows.

This means that to append to a specific line that is not at the end of the file you need to rewrite the whole file.

For example:

def file = new File("newFilename")
new File("output").withPrintWriter { out ->
    def linenumber = 1
    file.eachLine { line ->
        if (linenumber == 8)
            out.print(line)
            out.println("I wish to append this to line 8")
        } else {
            out.println(line)
        }
        linenumber += 1
    }
}
like image 196
ataylor Avatar answered Dec 05 '25 20:12

ataylor