tags:

views:

414

answers:

3

Hi,

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 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.

A: 

If you keep a reference to the underlying byte array output stream, you can call toString(String encoding) on it, or 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)

Brian Agnew
+5  A: 

Simply spoken: you can't. A PrintStream is for outputting, to read data, you need an InputStream (or any subclass).

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
Andreas_D
A: 

Since you can't change the controller, start a process for the controller and read from the process's output.

Example.

mcandre