In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
AppendLine() Appends the default line terminator to the end of the current StringBuilder object.
append(String str) method appends the specified string to this character sequence. The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument.
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).
I create original class that similar to StringBuidler and can append line by calling method appendLine(String str).
public class StringBuilderPlus {
private StringBuilder sb;
public StringBuilderPlus(){
sb = new StringBuilder();
}
public void append(String str)
{
sb.append(str != null ? str : "");
}
public void appendLine(String str)
{
sb.append(str != null ? str : "").append(System.getProperty("line.separator"));
}
public String toString()
{
return sb.toString();
}
}
Usage:
StringBuilderPlus sb = new StringBuilderPlus();
sb.appendLine("aaaaa");
sb.appendLine("bbbbb");
System.out.println(sb.toString());
Console:
aaaaa
bbbbb
For Kotlin,
StringBuilder().appendLine("your text");
Though this is a java question, this is also the first google result for Kotlin, might come in handy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With