Groovy write to file (newline)
Might be cleaner to use PrintWriter
and its method println
.
Just make sure you close the writer when you're done
I came across this question and inspired by other contributors. I need to append some content to a file once per line. Here is what I did.
class Doh {
def ln = System.getProperty('line.separator')
File file //assume it's initialized
void append(String content) {
file << "$content$ln"
}
}
Pretty neat I think :)
It looks to me, like you're working in windows in which case a new line character in not simply \n
but rather \r\n
You can always get the correct new line character through System.getProperty("line.separator")
for example.
As @Steven points out, a better way would be:
public void writeToFile(def directory, def fileName, def extension, def infoList) {
new File("$directory/$fileName$extension").withWriter { out ->
infoList.each {
out.println it
}
}
}
As this handles the line separator for you, and handles closing the writer as well
(and doesn't open and close the file each time you write a line, which could be slow in your original version)