33

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?

doelleri
  • 19,232
  • 5
  • 61
  • 65

4 Answers4

45

You should put the \n first. That way your newline will be written before your text:

f.append('\nhello again!')
Kai Sternad
  • 22,214
  • 7
  • 47
  • 42
11

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!'
}
Hafiz Adewuyi
  • 360
  • 4
  • 15
7

Groovy's concise syntax for writing into file:

f << '\n' << 'hello again'
Vasiliy Kevroletin
  • 1,188
  • 13
  • 17
  • Does this use a StringBuilder under the hood? – Andi Jay Aug 13 '18 at 15:11
  • I think [it should be](http://docs.groovy-lang.org/latest/html/gapi/org/codehaus/groovy/runtime/IOGroovyMethods.html#leftShift(java.lang.Appendable,%20java.lang.Object)) equivalent to series of `f.append(..)` calls like this `f.append('\n'); f.append('hello again');`. So the answer is that some other sort of buffering implemented in `f` is used. – Vasiliy Kevroletin Aug 14 '18 at 00:00
6

You can always get the correct new line character through

System.getProperty("line.separator")

so added it before your text

CodeIsLife
  • 1,205
  • 8
  • 14
  • you mean to add the line "System.getProperty("line.separator")" before the line --> f.append('hello again!\n') , ( sorry about the question I am very new in groovy ) –  May 01 '14 at 15:55
  • f.append(System.getProperty("line.separator")" + 'hello again!\n') – CodeIsLife May 01 '14 at 16:03
  • If you are building a lot of strings, then you should probably do something like: def nl=System.getProperty("line.separator"); After that your code would look like: f.append("${nl}hello again!"). It would allow you to create a short pattern you could use in many output statements. – Bill K Nov 29 '16 at 17:20