2014-06-25 55 views
0

我想使用Runtime類來執行一些UNIX命令,但如果我嘗試使用cd命令,則會出現問題。使用Java Runtime類運行多個unix命令

這裏是我的Java程序:

import java.io.*; 

public class JavaRunCommand { 

    public static void main(String args[]) { 

     String s = null; 

     try { 

      Process p = Runtime.getRuntime().exec("cd;cat test.txt|grep Hello"); 

      BufferedReader stdInput = new BufferedReader(new 
       InputStreamReader(p.getInputStream())); 

      BufferedReader stdError = new BufferedReader(new 
       InputStreamReader(p.getErrorStream())); 

      // read the output from the command 
      System.out.println("Here is the standard output of the command:\n"); 
      while ((s = stdInput.readLine()) != null) { 
       System.out.println(s); 
      } 

      // read any errors from the attempted command 
      System.out.println("Here is the standard error of the command (if any):\n"); 
      while ((s = stdError.readLine()) != null) { 
       System.out.println(s); 
      } 

      System.exit(0); 
     } 
     catch (IOException e) { 
      System.out.println("exception.."); 
      e.printStackTrace(); 
      System.exit(-1); 
     } 
    } 
} 

如果我執行這個然後我得到一個異常:

java.io.IOException: Cannot run program "cd": error=2, No such file or directory 
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041) 
    at java.lang.Runtime.exec(Runtime.java:617) 
    at java.lang.Runtime.exec(Runtime.java:450) 
    at java.lang.Runtime.exec(Runtime.java:347) 
    at JavaRunCommand.main(JavaRunCommand.java:11) 
Caused by: java.io.IOException: error=2, No such file or directory 
    at java.lang.UNIXProcess.forkAndExec(Native Method) 
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:135) 
    at java.lang.ProcessImpl.start(ProcessImpl.java:130) 
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1022) 
    ... 4 more 

請讓我知道我們如何能夠運行多個命令,如果我想在Java中使用它。

+1

'cd'是執行不是Binray。這是一個shell內置的命令。 –

+0

'cd'是一個傳遞給可執行文件'/ bin/sh'的參數。 –

+0

使用ProcessBuilder而不是Runtime.exec。 http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html –

回答

2

cd是一個用於遍歷目錄的內置shell命令。因此,它不是一個可以按照您嘗試的方式運行的實際unix命令。

最簡單的解決方案是在您要調用的命令中使用絕對路徑。例如,不要試圖運行"cd /my/dir; cat test.txt",只需致電"cat /my/dir/test.txt"即可。

3

如果更換

Process p = Runtime.getRuntime().exec("cd;cat test.txt|grep Hello"); 

Process p = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "cd && cat test.txt | grep Hello" }); 

它應該做的。

由於cd是內置shell命令,因此您需要調用shell來執行它。使用窗戶時,您需要撥打"cmd /c"

0

當您問及如何運行多個命令並以cd;cat test.txt|grep Hello爲例時,您需要sh來處理您的命令,因爲它不是一個可執行程序。

儘管安全隱患(*),你可以做

Process p = Runtime.getRuntime().exec("/bin/sh -c 'cd;cat test.txt|grep Hello'"); 

(*),它通常被認爲是一個糟糕的安全實踐不必要的命令可以根據環境