Java change system new-line character

On Windows, using System.out.println() prints out nr while on a Unix system you would get n.

Is there any way to tell java what new-line characters you want to use?

Answer

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.

Leave a Reply

Your email address will not be published. Required fields are marked *