Java change system new-line character

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.


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.