Reputation: 27632
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
Reputation: 8240
Do the following:
Runnable
run()
method write your codeSystem.out
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
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