[英]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())
; 当我尝试做
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? 当我尝试执行
System.out.println(byteStream.size())
,它显示0,这意味着在打印编写器写入ByteArrayOutputStream之后,字节缓冲区为空吗? I'm not sure if this is the only way to use PrintWriter to rite to byte array. 我不确定这是否是使用PrintWriter写入字节数组的唯一方法。 Is there another way to do this?
还有另一种方法吗?
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
自动刷新,并调用println
以包括换行字符。 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). PrintWriter
将刷新输出(如注释中已指出)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.