コード内でプロセスを実行してから、画面に両方の出力ストリーム(プロセスと私のもの)を表示することは可能ですか?
他のプロセスが自分のコードと並行して何をしているのかを確認する必要があります。
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()メソッドのコードです。