2012-04-23 64 views

回答

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

執行以下操作:

  1. 通過創建一個內部類從塊由System.out
  2. 輸出由System.out從外部啓動一個新的線程,並延伸Runnable
  3. run()方法編寫代碼
  4. 輸出代碼主線程的代碼的 區塊。

內部類是啓動新進程(線程)最適當的方法。我所指的塊是run()方法中的代碼。

+0

爲什麼* inner * class?第3項和第4項中提到的「塊」*是什麼? – aioobe 2012-04-23 11:09:04

+0

內部類是啓動新進程(線程)最適當的方式。我所指的塊是run()方法中的代碼 – GingerHead 2012-04-23 11:35:10