• Post Reply Bookmark Topic Watch Topic
  • New Topic

StringBuffer containing '\n'

 
Bob Green
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following stringbuffer
StringBuffer sb = new StringBuffer("This is first line");
sb.append("\n");
sb.append("This is second line");
sb.append("\n");

And I need to write this stringbuffer to a file hoping that
some IO classes would help to recognize the '\n' character.

The file should look like this:
This is first line
This is second line

I would like to know if it is doable with the available IO classes
and if so, can you pls. let me know.

Thanks!
 
Joe Ess
Bartender
Posts: 9361
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Line separator characters are not platform independent. On Windows, for example, the line separator is "\n\r". The output you've generated may indeed look like what you expect if you view it with a program that recognizes "\n" as the separator. Most programmer's source code editors can be configured to. In your case, your best bet is to use System.getProperties() to obtain the line seperator for your platform and use it in place of your hard coded "\n". There are several places in the IO API where line separation is handled platform independently, for example, PrintWriter.println() and BufferedWriter.newLine().
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!