2017-04-06 22 views
0

所以我想在我的Linux計算機上運行一個進程,並且在發送過程中輸出該進程的輸出,例如(我剛剛提出):如何從運行過程中獲得直接輸出?

一個不斷運行的進程輸出每五秒一個隨機數

52 
72 
33 
67 
26 
74 
2 

我想在打印到控制檯時得到數字。

目前,我有一些代碼,可以用於執行命令的工作,雖然我不知道,即使工作:

public OutputStream executeCommand(String command) { 
    try { 
     ProcessBuilder pb = new ProcessBuilder(command);  
     Process p = pb.start(); 
     OutputStream ops = p.getOutputStream(); 
     return ops; 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return null; 
} 

我幾乎只是問我怎麼能拿某種輸出並在打印時讀取它。

回答

1

請注意以下代碼可能會拋出IOException。

Runtime runtime = Runtime.getRuntime() ; 
      Process process = runtime.exec("Your command") ; 
      BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())) ; 
      String line = null ; 
      while ((line = reader.readLine())!= null){ 
       System.out.println(line); 
      } 
相關問題