Java:如何从 PrintStream 读取数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1207281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How do I read from PrintStream?
提问by Midnight Blue
I am trying to read(append incoming data into a local String) from a PrintStram in the following code block:
我正在尝试从以下代码块中的 PrintStram 读取(将传入数据附加到本地字符串中):
System.out.println("Starting Login Test Cases...");
out = new PrintStream(new ByteArrayOutputStream());
command_feeder = new PipedWriter();
PipedReader in = new PipedReader(command_feeder);
main_controller = new Controller(in, out);
for(int i = 0; i < cases.length; i++)
{
command_feeder.write(cases[i]);
}
main_controller will be writing some strings to its out(PrintStream), then how can I read from this PrintStream assuming I can't change any code in Controller class? Thanks in advance.
main_controller 将向其输出(PrintStream)写入一些字符串,那么假设我无法更改 Controller 类中的任何代码,我如何从该 PrintStream 中读取?提前致谢。
回答by Andreas Dolk
Simply spoken: you can't. A PrintStream is for outputting, to read data, you need an InputStream (or any subclass).
简单地说:你不能。PrintStream 用于输出,要读取数据,您需要一个 InputStream(或任何子类)。
You already have a ByteArrayOutputStream. Easiest to do is:
您已经有一个 ByteArrayOutputStream。最简单的做法是:
// ...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
out = new PrintStream(baos);
// ...
ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray());
// use in to read the data
回答by Brian Agnew
If you keep a reference to the underlying byte array output stream, you can call toString(String encoding)on it, or toByteArray().
如果您保留对底层字节数组输出流的引用,则可以对其调用toString(String encoding)或toByteArray()。
I suspect you want the former, and you need to specify the encoding to match how the strings have been written in (you may be able to get away with using the default encoding variant)
我怀疑您想要前者,并且您需要指定编码以匹配字符串的写入方式(您可能可以使用默认编码变体)

