252

I have a StringBuilder object,

StringBuilder result = new StringBuilder();
result.append(someChar);

Now I want to append a newline character to the StringBuilder. How can I do it?

result.append("/n"); 

Does not work. So, I was thinking about writing a newline using Unicode. Will this help? If so, how can I add one?

Adam Stelmaszczyk
  • 18,835
  • 4
  • 63
  • 104
Illep
  • 14,274
  • 40
  • 148
  • 258
  • 24
    I thought it is `"\n"`, or [`System.getProperty("line.separator")`](http://stackoverflow.com/questions/247059/is-there-a-newline-constant-defined-in-java-like-environment-newline-in-c). – Alvin Wong Jan 26 '13 at 07:16
  • A [newline](https://en.wikipedia.org/wiki/Newline) is not necessarily a LINE FEED (LF) (Ascii/Unicode 10) character. As the [correct answer](http://stackoverflow.com/a/14534798/642706) points out, in Java you can get either one (LINE FEED or a platform-specific newline). – Basil Bourque Mar 18 '14 at 03:54

8 Answers8

547

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()

Jayamohan
  • 12,059
  • 2
  • 25
  • 39
  • 95
    +1 for the System.lineSeparator shortcut. The bigger question is why there isn't a `StringBuilder#appendLine()` method. – Patrick M Mar 11 '15 at 19:26
  • 16
    `System.lineSeparator()` documentation mentions "Returns the system-dependent line separator string.". This is not platform independant. Use this code if you need to write a string that will be used by the underlying operating system, otherwise use `'\n'`. – tuscland Jun 02 '15 at 07:05
  • 2
    @tuscland - Why not just use System.lineSeparator() all the time? Why is '\n' a better option as default? – RyanfaeScotland Jun 03 '15 at 15:46
  • 17
    No, `System.lineSeparator()` should be used when you deal with non-portable resources (that is, resources specific to the underlying operating system). It has a different value wether you are running Java on Windows (\r\n) or Unix (\n). If you use `System.lineSeparator()` all the time, you will therefore produce non portable files. – tuscland Jun 04 '15 at 16:26
  • 7
    Unbelievable there's not already an `appendLine` overload on `StringBuilder`. – Josh M. Jun 21 '18 at 18:54
  • System.getProperty("line.separator") works in sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, digipaz.toString()); – sirmagid Apr 22 '19 at 06:34
  • Any Android devs using Kotlin that may have stumbled here, this is what you're looking for https://stackoverflow.com/a/57705139/2445763 – lasec0203 Sep 19 '19 at 12:41
  • In Kotlin I still just add "\n" to my string when I need it... – The incredible Jan Mar 01 '21 at 13:09
23

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

Half_Duplex
  • 3,653
  • 3
  • 24
  • 46
  • 5
    ... and since Java 8 there's [StringJoiner](https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html), which "_is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix._" Using "\n" as delimiter would result in new lines (except for the last one). Internally, it uses a StringBuilder. The same approach could be realized using the Google Guava Joiner, I assume. – jechterhoff Dec 06 '17 at 10:48
  • 1
    ... and now this is `deprecated`. Please use `org.apache.commons.text.TextStringBuilder`. – Ashok M A Jan 24 '19 at 11:50
  • `TextStringBuilder` is not in `commons-lang3`, it is in `commons-text` https://commons.apache.org/proper/commons-text/ – Salvatorelab Jan 21 '21 at 09:26
17

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).

nhahtdh
  • 52,949
  • 15
  • 113
  • 149
3

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
K.S
  • 77
  • 4
2

you can use line.seperator for appending new line in

Illep
  • 14,274
  • 40
  • 148
  • 258
Rashida Hasan
  • 99
  • 2
  • 11
1

You can also use the line separator character in String.format (See java.util.Formatter), which is also platform agnostic.

i.e.:

result.append(String.format("%n", ""));

If you need to add more line spaces, just use:

result.append(String.format("%n%n", ""));

You can also use StringFormat to format your entire string, with a newline(s) at the end.

result.append(String.format("%10s%n%n", "This is my string."));
ostrichofevil
  • 689
  • 6
  • 18
Roxanne
  • 35
  • 5
1

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.

sunadorer
  • 3,700
  • 29
  • 40
farhan patel
  • 1,316
  • 2
  • 17
  • 27
0

In addition to K.S's response of creating a StringBuilderPlus class and utilising ther adapter pattern to extend a final class, if you make use of generics and return the StringBuilderPlus object in the new append and appendLine methods, you can make use of the StringBuilders many append methods for all different types, while regaining the ability to string string multiple append commands together, as shown below

public class StringBuilderPlus {

    private final StringBuilder stringBuilder;

    public StringBuilderPlus() {
        this.stringBuilder = new StringBuilder();
    }

    public <T> StringBuilderPlus append(T t) {
        stringBuilder.append(t);
        return this;
    }

    public <T> StringBuilderPlus appendLine(T t) {
        stringBuilder.append(t).append(System.lineSeparator());
        return this;
    }

    @Override
    public String toString() {
        return stringBuilder.toString();
    }

    public StringBuilder getStringBuilder() {
        return stringBuilder;
    }
}

you can then use this exactly like the original StringBuilder class:

StringBuilderPlus stringBuilder = new StringBuilderPlus();
stringBuilder.appendLine("test")
    .appendLine('c')
    .appendLine(1)
    .appendLine(1.2)
    .appendLine(1L);

stringBuilder.toString();
Qualia91
  • 123
  • 1
  • 7