1
votes

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.

3
If you simply want to know what the Controller is doing, then create it with 'new Controller(in, System.out)' and it will write to the console (standard out)Andreas Dolk

3 Answers

9
votes

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
0
votes

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)

0
votes

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

Example.