Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"\n" not adding new line when saving the string to text using PrintWriter

I want to print a string to a text using out.print but the \n in the string are not working.

Here is the code:

import java.io.PrintWriter;

public class LetterRevisited{
    public static void main(String[] args)throws Exception
    {
        PrintWriter out = new PrintWriter("Test.txt");
        out.println("This is the first line\n" +
        "This is the second line" );
    out.close();
    }
}

But in the saved file no new line is created, all the lines are after each other. Any idea how to fix this? (beside adding out.println to all lines.)

Edit: I compile and run the code with windows command prompt and open the file with notepad.

like image 723
farshad Avatar asked Dec 10 '22 17:12

farshad


2 Answers

Different platforms use different line separators.

  • Windows use \r\n
  • Unix-like platforms use \n
  • Mac now uses \n too, but it used to use \r.

(You can see more information and variants here)

You can get your "local" line separator by using

System.getProperty("line.separator")

e.g.

out.println("Hello" + System.getProperty("line.separator") + "World");

However, it is easier to use %n in a string formatter:

out.printf("Hello%nWorld%n");

If you are targeting a particular platform, you can just use the literal.

like image 176
Andy Turner Avatar answered Jan 16 '23 05:01

Andy Turner


If you are using Java 7 then you can use System.lineSeparator()..see if this helps. For older versions of Java you can use - System.getProperty("line.separator")

Example : System.out.println(System.lineSeparator()+"This is the second line");

like image 42
Shiv Gopal Avatar answered Jan 16 '23 06:01

Shiv Gopal