MBZ
MBZ

Reputation: 27632

view output stream of a process in addition to my own

is it possible to run a process inside my code and then see both output streams (the process and mine) on the screen?

I need to see what the other process doing in parallel with my own code!

Upvotes: 0

Views: 156

Answers (2)

GingerHead
GingerHead

Reputation: 8240

Do the following:

  1. Start a new thread by creating an inner class and extend Runnable
  2. In the run() method write your code
  3. Output your code from your block by System.out
  4. Output the main thread's code by System.out from outside your block.

The inner class is the most adequate way to initiate a new process (thread). The block I am referring to is your code in the run() method.

Upvotes: 0

aioobe
aioobe

Reputation: 421310

You need to start a thread which reads data from the Process output stream, and prints it on System.out.

You can use a class like this:

class ProcessOutputStreamPrinter extends Thread {

    BufferedReader reader;

    public ProcessOutputStreamPrinter(Process p) {
        reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    }

    public void run() {
        try {
            String line;
            while (null != (line = reader.readLine()))
                System.out.println("Process output: " + line);
        } catch (IOException e) {
            // handle somehow
        }
    }
}

Here's some test code for that class:

class Test {
    public static void main(String[] args) throws IOException {

        // Start external process. (Replace "cat" with whatever you want.)
        ProcessBuilder pb = new ProcessBuilder("cat");
        Process p = pb.start();

        // Start printing it's output to System.out.
        new ProcessOutputStreamPrinter(p).start();

        // Just for testing:

        // Print something ourselves:
        System.out.println("My program output: hello");

        // Give cat some input (which it will echo as output).
        PrintWriter pw = new PrintWriter(new PrintStream(p.getOutputStream()));
        pw.println("hello");
        pw.flush();

        // Close stdin to terminate "cat".
        pw.close();
    }
}

Output:

My program output: hello
Process output: hello

Upvotes: 1

Related Questions