Reputation: 105
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
Reputation: 178333
Your output needs to be flushed to the stream. You can do one of the following:
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");
PrintWriter pw = new PrintWriter(byteStream);
pw.write("TEST STRING");
pw.flush();
PrintWriter
flushes the output (as already indicated in a comment).Upvotes: 4