How to append a newline to StringBuilder How to append a newline to StringBuilder java java

How to append a newline to StringBuilder


It should be

r.append("\n");

But I recommend you to do as below,

r.append(System.getProperty("line.separator"));

System.getProperty("line.separator") gives you system-dependent newline in java. Also from Java 7 there's a method that returns the value directly: System.lineSeparator()


Another option is to use Apache Commons StrBuilder, which has the functionality that's lacking in StringBuilder.

StrBuilder.appendLn()

As of version 3.6 StrBuilder has been deprecated in favour of TextStringBuilder which has the same functionality


Escape should be done with \, not /.

So r.append('\n'); or r.append("\n"); will work (StringBuilder has overloaded methods for char and String type).