coppthi
coppthi

Reputation: 105

Using printWriter to write to a byte buffer?

I wasn't sure if this was possible. I tried doing something like

ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(byteStream);
pw.write("TEST STRING");

When I try to do System.out.println(byteStream.toString()); It prints an empty string. When I try to do System.out.println(byteStream.size()), it prints 0, meaning the byte buffer in ByteArrayOutputStream is empty after print writer writes to it? I'm not sure if this is the only way to use PrintWriter to rite to byte array. Is there another way to do this?

Upvotes: 1

Views: 2136

Answers (1)

rgettman
rgettman

Reputation: 178333

Your output needs to be flushed to the stream. You can do one of the following:

  1. Make the PrintWriter auto-flushable using the appropriate constructor and call println to include a line-feed character.
PrintWriter pw = new PrintWriter(byteStream, true);
pw.println("TEST STRING");
  1. Or, you can flush it explicitly.
PrintWriter pw = new PrintWriter(byteStream);
pw.write("TEST STRING");
pw.flush();
  1. Closing the PrintWriter flushes the output (as already indicated in a comment).

Upvotes: 4

Related Questions