问题描述
我正在尝试从以下代码块中的PrintStram读取(将传入数据附加到本地String中):
I am trying to read(append incoming data into a local String) from a PrintStram in the following code block:
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会将一些字符串写入其中(PrintStream),那怎么能我从这个PrintStream中读取,假设我无法更改Controller类中的任何代码?在此先感谢。
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.
推荐答案
简单地说:你做不到。 PrintStream用于输出,要读取数据,您需要一个InputStream(或任何子类)。
Simply spoken: you can't. A PrintStream is for outputting, to read data, you need an InputStream (or any subclass).
您已经有了一个ByteArrayOutputStream。最容易做的是:
You already have a ByteArrayOutputStream. Easiest to do is:
// ...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
out = new PrintStream(baos);
// ...
ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray());
// use in to read the data
这篇关于Java:我如何从PrintStream中读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!