简体   繁体   中英

Java: PrintWriter and newlines in a string

My question is pretty straight forward, if I have a single long string with alot of "\\n" newlines within it, ie:

strings = "Hey\nThere\nFriend\n"

And use a PrintWriter in Java to do the following:

PrintWriter save = new PrintWriter("test.txt");
save.println(strings);
save.close();

Will the file I end up with be formatted with the \\n? ie the file will have:

Hey
There
Friend

Or will it have:

Hey\nThere\nFriend

If it's the latter, can someone guide me on how I might change my code (and understanding of how PrintWriter works) to create the former output?

In fact, \\n will work but only for Unix based OS. Windows based OS use \\r\\n as separator.

You should avoid using specific OS line separator if you want to write a portable code.
Favor System.lineSeparator() to not be OS dependent.
Note also that PrintWriter provides println() to achieve a break line that is not OS dependent (even if it is not necessary useful for you use case)

You will get a text file containing a single text line Hey\\nThere\\nFriend\\n followed by your operating system new-line sequence (inserted by println() ).

The meaning of \\n depends on the operating system and possibly the text editor. On Linux \\n usually will be interpreted as new-line sequence but on Windows the new-line sequence is \\r\\n so most text editors (eg native Notepad) will display a single HeyThereFriend line.

On windows platform \\n means char(13) +Char(10) you can use

String nl = Character.toString ((char) 13)+Character.toString ((char) 10);  
String strings = "Hey"+nl+"There"+nl+"Friend"+nl;
System.out.print(strings);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM