[java] How to create a String with carriage returns?

For a JUnit test I need a String which consists of multiple lines. But all I get is a single lined String. I tried the following:

    String str = ";;;;;;\n" +
                 "Name, number, address;;;;;;\n" + 
                 "01.01.12-16.02.12;;;;;;\n" + 
                 ";;;;;;\n" + 
                 ";;;;;;";

I also tried \n\r instead of \n. System.getProperty("line.separator") doesn't work too. it produces a \n in String and no carriage return. So how can I solve that?

This question is related to java string

The answer is


Try \r\n where \r is carriage return. Also ensure that your output do not have new line, because debugger can show you special characters in form of \n, \r, \t etc.


Do this: Step 1: Your String

String str = ";;;;;;\n" +
            "Name, number, address;;;;;;\n" + 
             "01.01.12-16.02.12;;;;;;\n" + 
             ";;;;;;\n" + 
             ";;;;;;";

Step 2: Just replace all "\n" with "%n" the result looks like this

String str = ";;;;;;%n" +
             "Name, number, address;;;;;;%n" + 
             "01.01.12-16.02.12;;;;;;%n" + 
            ";;;;;;%n" + 
            ";;;;;;";

Notice I've just put "%n" in place of "\n"

Step 3: Now simply call format()

str=String.format(str);

That's all you have to do.


It depends on what you mean by "multiple lines". Different operating systems use different line separators.

In Java, \r is always carriage return, and \n is line feed. On Unix, just \n is enough for a newline, whereas many programs on Windows require \r\n. You can get at the platform default newline use System.getProperty("line.separator") or use String.format("%n") as mentioned in other answers.

But really, you need to know whether you're trying to produce OS-specific newlines - for example, if this is text which is going to be transmitted as part of a specific protocol, then you should see what that protocol deems to be a newline. For example, RFC 2822 defines a line separator of \r\n and this should be used even if you're running on Unix. So it's all about context.


Try append characters .append('\r').append('\n'); instead of String .append("\\r\\n");


The fastest way I know to generate a new-line character in Java is: String.format("%n")

Of course you can put whatever you want around the %n like:

String.format("line1%nline2")

Or even if you have a lot of lines:

String.format("%s%n%s%n%s%n%s", "line1", "line2", "line3", "line4")