0
A
回答
2
您需要啓動一個從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
0
執行以下操作:
- 通過創建一個內部類從塊由
System.out
- 輸出由
System.out
從外部啓動一個新的線程,並延伸Runnable
- 在
run()
方法編寫代碼 - 輸出代碼主線程的代碼的 區塊。
內部類是啓動新進程(線程)最適當的方法。我所指的塊是run()方法中的代碼。
相關問題
- 1. 查看後臺進程的輸出
- 2. 自己的輸出流(模擬COUT)
- 3. 如何禁止用戶查看除自己下線以外的其他成員?
- 4. 在Xcode中查看我自己的HeaderDoc
- 5. 查看我自己的instagram照片?
- 6. 製作我自己的API,請查看
- 7. 我可以創建與stdout和stderr不同的自己的輸出流嗎?
- 8. 爲我自己的類重載輸出流
- 9. 爲什麼我自己的輸出流類不工作?
- 10. 拋出我自己的例外?
- 11. 帶輸入/輸出流的Java進程
- 12. 輸入自己的類輸入流?
- 13. 查找我自己.NET進程的所有子進程/查明給定進程是否屬於我自己的子進程?
- 14. Ruby中的子進程的流輸出
- 15. 以編程方式刪除我自己的應用程序
- 16. SQL:根據查詢輸出打印我自己的消息
- 17. 在linux中查看已經運行的進程的輸出
- 18. 程序是否可以輸出自己的副本
- 19. 我可以查看我的舊.zsh_history輸出
- 20. 將除成功流以外的所有輸出流重定向到文件
- 21. 可以通過外部進程查看php導出的變量嗎?
- 22. 查看getRootView返回自己
- 23. 需要在VB6中查找我自己的進程ID
- 24. 如何查看運行Linux進程的輸出結果^
- 25. 如何自動插入外鍵而不必自己查看?
- 26. 我可以暫停除一個線程之外的進程嗎?
- 27. C++自定義輸出流與縮進
- 28. 編寫我自己的查找程序時出現Seg錯誤
- 29. 使用除10以外的其他鹼基的輸入流進行讀取
- 30. Android onAnimationEnd刪除查看(自己)不刪除
爲什麼* inner * class?第3項和第4項中提到的「塊」*是什麼? – aioobe 2012-04-23 11:09:04
內部類是啓動新進程(線程)最適當的方式。我所指的塊是run()方法中的代碼 – GingerHead 2012-04-23 11:35:10