是否可以在我的代码中运行一个进程,然后在屏幕上看到两个输出流(进程和我的)?
我需要查看其他进程与我自己的代码并行执行的操作!
您需要启动一个线程,该线程从Process
输出流中读取数据,并将其打印在System.out
.
您可以使用这样的类:
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
}
}
}
这是该类的一些测试代码:
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();
}
}
输出:
My program output: hello
Process output: hello
请执行下列操作:
Runnable
run()
方法中写下你的代码System.out
System.out
从块外部 输出主线程的代码。内部类是启动新进程(线程)的最适当方式。我所指的块是您在 run() 方法中的代码。