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.
Different platforms use different line separators.
\r\n
\n
\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.
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");
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