On Windows, using System.out.println()
prints out \n\r
while on a Unix system you would get \n
.
Is there any way to tell java what new-line characters you want to use?
Use this: text = text. replace(", ", "\n");
'\r' is the representation of the special character CR (carriage return), it moves the cursor to the beginning of the line. '\n'(line feed) moves the cursor to the next line . On windows both are combined as \r\n to indicate an end of line (ie, move the cursor to the beginning of the next line).
\n is a line feed (LF) character, character code 10. \r is a carriage return (CR) character, character code 13. What they do differs from system to system. On Windows, for instance, lines in text files are terminated using CR followed immediately by LF (e.g., CRLF).
Replace new line (\n) with HTML br tag in string using Java uses the \n character, also known as Line Feed (LF) character, to move the cursor to the next line. Windows uses \r\n characters to specify the start of the line, sometimes also called Carriage Return and Line Feed (CRLF).
As already stated by others, the system property line.separator
contains the actual line separator. Strangely, the other answers missed the simple conclusion: you can override that separator by changing that system property at startup time.
E.g. if you run your program with the option -Dline.separator=X
at the command line you will get the funny behavior of System.out.println(…);
ending the line with an X
.
The tricky part is how to specify characters like \n
or \r
at the command line. But that’s system/environment specific and not a Java question anymore.
Yes, there is a way and I've just tried it.
There is a system property line.separator
. You can set it using System.setProperty("line.separator", whatever)
To be sure that it indeed causes JVM to use other separator I implemented the following exercise:
PrintWriter writer = new PrintWriter(new FileWriter("c:/temp/mytest.txt"));
writer.println("hello");
writer.println("world");
writer.close();
I am running on windows now, so the result was 14 bytes long file:
03/27/2014 10:13 AM 14 mytest.txt
1 File(s) 14 bytes
0 Dir(s) 409,157,980,160 bytes free
However when I added the following line to the beginning of my code:
System.setProperty("line.separator", "\n");
I got 14 bytes long file:
03/27/2014 10:13 AM 14 mytest.txt 1 File(s) 14 bytes 0 Dir(s) 409,157,980,160 bytes free
I opened this file with notepad that does not recognize single \n
as a new line and saw one-line text helloworld
instead of 2 separate lines. So, this works.
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