Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Files.write losing \n character  RSS feed

 
Jacob Morehouse
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi again,


OK, I'm stumped. When I System.out.println() the text looks great and the newline/line breaks appear normally. But when I save the string to a file they all appear on one line.

The newline characters just disappear. I've tried with no charset (letting in default), UTF-8, and US-ASCII. None of those made a noticeable difference. What am I doing wrong here?

Thanks,
Jake
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Windows doesn't use \n for linebreaks (as Unix/Linux does), but the sequence \r\n. It's up to the application displaying the file to be smart about recognizing both, but not all do.

See the javadocs of the BufferedWriter class for how to write code that does the right thing based on which platform it's running. (Of course, files get interchanged between OSes, so that's not a panacea.)
 
Campbell Ritchie
Marshal
Posts: 55681
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stop using MS Notepad. Use a different text editor; some of them even show a box asking for the line end type when opening text files created on other computers.
 
Jacob Morehouse
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it, thanks Ulf Dittmer!

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!