Why does the following Groovy code not append the "hello again" on a new line?
f = new File('myfile.txt')
f.append('hello again!\n')
This adds to myfile.txt after the last line but not on a new line. How do I append the text on a new line?
Why does the following Groovy code not append the "hello again" on a new line?
f = new File('myfile.txt')
f.append('hello again!\n')
This adds to myfile.txt after the last line but not on a new line. How do I append the text on a new line?
You should put the \n
first. That way your newline will be written before your text:
f.append('\nhello again!')
Yet another way of doing this. In this case, you don't have to add the newline character manually
File greetingsFile = new File("myfile.txt")
greetingsFile.withWriterAppend{ out ->
out.println 'hello again!'
}
Groovy's concise syntax for writing into file:
f << '\n' << 'hello again'
You can always get the correct new line character through
System.getProperty("line.separator")
so added it before your text