简体   繁体   English

使用printWriter写入字节缓冲区?

[英]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: 您可以执行以下操作之一:

  1. Make the 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");
  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). 关闭PrintWriter将刷新输出(如注释中已指出)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM