2015-11-02 68 views
4

我需要從我的Java應用程序運行命令並處理它的輸出。 的代碼是這個樣子:從Java執行本地OS命令時沒有輸出

public static void readAllOutput(){ 
     try { 
      final String cmd = new String("find ~ -iname \"screen*\""); 
      System.out.println(cmd); 
      Process ps = Runtime.getRuntime().exec(cmd); 
//   ps.waitFor(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(ps.getInputStream())); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       System.out.println(line); 
      } 
     } catch (IOException /*| InterruptedException*/ e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

當我執行該命令從OS我有一個大的輸出,但在我的Java應用程序的輸出是emty。

+2

我在想''''(user dir)是不是最好用'System.getProperty(「user.home」)填充''。另外** ProcessBuilder **是一個實用程序類,簡化了處理。同時通過在同一時間讀取錯誤流來循環。 –

+1

請重構您的代碼ProcessBuilder – Jayan

+3

〜,*等由Shell擴展。你的過程(找到...)不會這樣做。另一種方法是將bash -c 視爲子進程 – Jayan

回答

2

你需要使用

getRuntime().exec(new String[] { "find", "~", "-iname","screen*"}); 

,或者嘗試

getRuntime().exec(new String[] { "find", "~", "-iname","\"screen*\""}); 

序接受參數作爲雙引號。