1

I need to write strings into ByteArrayOutputStream, but I need to write strings with breaking. I have tried to do it as example:

out.write("123".getBytes());
out.write("\n456".getBytes());

But '\n' doesn't work. Please, tell me, how can I fix it? Or suggest me alternative OutputStream for storing strings (this OS must allow to use breaking of lines) without making files. Thank you.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
user1134602
  • 597
  • 1
  • 4
  • 11
  • 2
    What do you mean by breaking? – Mike Samuel Jan 12 '12 at 19:07
  • I mean that each string is another line on file. – user1134602 Jan 12 '12 at 19:09
  • Which OS? If it's Windows you might need "\r\n" for a linebreak if you're writing it as bytes, depending on what you then try to read the file with. – Rup Jan 12 '12 at 19:10
  • 1
    What is "this OS"? Maybe you need to use the newline sequence for your OS. The LF (\n) works for unix-like OSes, but Windows uses CR-LF (\r\n). You can find it programmatically with `System.getProperty("line.separator")`: http://stackoverflow.com/questions/207947/java-how-do-i-get-a-platform-independent-new-line-character – jbindel Jan 12 '12 at 19:12
  • Please clarify your statement that "'\n' doesn't work". It *does* work, in that it does exactly what it's supposed to. The problem is that you want something different . . . but you haven't said what that is. – ruakh Jan 12 '12 at 19:12
  • @Fly: "this OS" must mean "this OutputStream", i.e., the "alternative OutputStream for storing strings" that the OP is soliciting suggestions for. – ruakh Jan 12 '12 at 19:13

3 Answers3

7
ByteArrayOutputStream stream = ...;
PrintStream printer = new PrintStream(stream, true); // auto-flush
printer.println("123"); // writes newline
printer.print("hello"); // no new line
printer.print(" world");
printer.println();

Note that this will generate platform-specific bytes. Newlines can be \n, \r\n or \r. The actual character sequence used is specified in system property line.separator.

Dilum Ranatunga
  • 13,254
  • 3
  • 41
  • 52
3

Just use BufferedWriter it will manage line breaks for you (bwinstance.newLine()). No matter on which OS you are running.

gorootde
  • 4,003
  • 4
  • 41
  • 83
  • There's a step missing: you can't go from an OutputStream to a BufferedWriter directly. You need to already have a Writer (such as an OutputStreamWriter) to buffer. – Ted Hopp Jan 12 '12 at 19:14
3

If you are looking for a system independent newline separator I would recommend using:

System.getProperty("line.separator");

Rather than calling getProperty() every time, I would also store this value in a properly accessible variable.

This is also the ideal method if you are constructing strings prior to writing them, since this way you will not have to write each line separately.

gnomed
  • 5,483
  • 2
  • 26
  • 28