Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to save a text file without boxes for newline character?

 
Bob Zoloman
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have a program that opens a text file and displays it's contents in a textfield. When I load the file I use the following statement to add the contents to the textfield:



The content in the textfield is exactly like the input text file. When I go
to save the file it adds little boxes for the \n character. If I remove the \n characters before saving it puts the text on one line... How can I save the file, so it doesn't display little box characters for newline characters while keeping the output the same as the input. Thanks in advance.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where do you see those little boxes? When you open the file in Notepad or in another text editor?

Different operating systems use different sequences of bytes to represent newlines. On Unix, usually one character is used (LF = linefeed = ASCII code 10). On Windows, CR LF (carriage return + linefeed, ASCII codes 13 and 10) are used.

If you write a file with line separators that are different from what the native OS uses, or from what your text editor expects, you might see those boxes.

Use File.separator instead of "\n" to make sure that you're using the end-of-line character sequence of the platform that your program is running on.
 
Bob Zoloman
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I replaced "\n" to File.Separator it shows up as a forward slash.
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper meant to use System.getProperty("line.separator"), but you shouldn't put that into a text component: they're designed to use '\n' as their line separator. That property is really only good for writing newlines in a system-dependent way, but you don't need it even for that; just use one of the println() methods of your OutputStream/Writer.

The only real problem here is that Notepad is too stupid to handle anything but the DOS-style "\r\n" line separator. I wonder if they'll finally fix that in Vista?
 
Bob Zoloman
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah so obvious, thanks for that tip!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic