2012-08-13 42 views
0

我有一個問題,用r.exec調用一些簡單的命令行函數 - 出於某種原因,給定一個文件X命令 'echo完整/路徑/到/ X'工作正常(在顯示和'p.exitValue()== 0',但'貓滿/路徑/到/ X'不(並具有'p.exitValue() == 1') - 'cat'和'echo'都位於/ bin /我的OSX上 - 我是否缺少某些東西?代碼在下面(因爲它發生了,任何改善代碼的建議都會受到歡迎...)Runtime.exec - 適用於'echo''但不適用於貓...

private String takeCommand(Runtime r, String command) throws IOException { 
     String returnValue; 
     System.out.println("We are given the command" + command); 
     Process p = r.exec(command.split(" ")); 
     InputStream in = p.getInputStream(); 
     BufferedInputStream buf = new BufferedInputStream(in); 
     InputStreamReader inread = new InputStreamReader(buf); 
     BufferedReader bufferedreader = new BufferedReader(inread); 
     // Read the ls output 
     String line; 
     returnValue = ""; 
     while ((line = bufferedreader.readLine()) != null) { 
      System.out.println(line); 
      returnValue = returnValue + line; 
     } 
     try {// Check for failure 
      if (p.waitFor() != 0) { 
       System.out.println("XXXXexit value = " + p.exitValue()); 
      } 
     } catch (InterruptedException e) { 
      System.err.println(e); 
     } finally { 
      // Close the InputStream 
      bufferedreader.close(); 
      inread.close(); 
      buf.close(); 
      in.close(); 
     } 
     try {// should slow this down a little 
      p.waitFor(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     return returnValue; 
    } 
+1

如果您使用ProcessBuilder,則可以將stdout和stderr結合使用,以便只有一個流可以讀取。 – 2012-08-13 10:36:25

回答

2

你應該消耗輸出和錯誤異步

否則命令的輸出可能會阻塞輸入緩衝區,然後一切都會停止(這可能是因爲cat命令發生了什麼,因爲它會轉儲比echo更多的信息)。

我也不期望必須撥打waitFor()兩次。

檢查出this SO answer有關輸出消耗的更多信息,並且this JavaWorld文章更多Runtime.exec()陷阱。

相關問題