Java: How to read from PrintStream?

I am trying to read (add incoming data to a local line) from 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 will write some lines to its file (PrintStream), then how can I read from this PrintStream, assuming that I cannot change any code in the controller class? Thanks in advance.

0
java io
source share
3 answers

Simply put: you cannot. PrintStream is for output, for reading data you need an InputStream (or any subclass).

You already have a ByteArrayOutputStream. The easiest way:

 // ... ByteArrayOutputStream baos = new ByteArrayOutputStream(); out = new PrintStream(baos); // ... ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray()); // use in to read the data 
+8
source share

If you keep a reference to the output stream of the underlying byte array, you can call toString (String encoding) on it or toByteArray () .

I suspect you need the first one, and you need to specify an encoding to match how the lines were written (you can get away using the default encoding option)

0
source share

Since you cannot change the controller, start the process for the controller and read it from the output of the process.

An example .

0
source share

All Articles