Q:

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

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")

A:

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
    }
}

A:

For small files you can use the following piece of code:
def f = new File('file')
def lines = f.readLines()
lines = lines.plus(7, "I'm a new line!")
f.text = lines.join('\n')

