2014-09-01 95 views
1

爲什麼我收到以下錯誤:有運行Linux在Java命令麻煩

Exception in thread "main" java.io.IOException: Cannot run program "cd": error=2, No such file or directory 
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048) 
at com.terminal.Main.main(Main.java:20) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:483) 
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134) 
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:187) 
at java.lang.ProcessImpl.start(ProcessImpl.java:134) 
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029) 
... 6 more 

這裏是我使用的代碼:

Runtime.getRuntime().exec("cd ~/"); 
Process pwd = Runtime.getRuntime().exec("pwd"); 
try (Scanner scanner = new Scanner(pwd.getInputStream())) { 
    while (scanner.hasNextLine()) { 
     System.out.println(scanner.nextLine()); 
    } 
} 

還當我嘗試執行其他一些命令,作爲sudo./,IOException再次發生... 有什麼問題?任何想法傢伙?

謝謝:)

+0

您需要一個解釋器(shell)來運行* cd *命令。 * cd *本身不是可執行程序。 – agad 2014-09-01 14:25:04

回答

0

正如阿加德所說,cd不是一個程序,它是一個shell命令。要改變工作目錄爲您的exec()調用,使用three argument method

try { 
    File wd = new File("~/"); 
    Process pwd = Runtime.getRuntime().exec("pwd", null, wd); 
    Scanner scanner = new Scanner(pwd.getInputStream()); 
    while (scanner.hasNextLine()) { 
     System.out.println(scanner.nextLine()); 
    } 
} 
catch (Exception e) { 
    System.out.println(e.getMessage()); 
} 

正如你可能已經注意到,因爲使用波浪號作爲主目錄一提的是另一本代碼仍然會返回一個錯誤貝殼利益。你可以替換「〜/」與主目錄,或者更可能的情況下,它是未知的,你可以使用下面的代碼來獲取目錄:

try { 
    String homedir = System.getProperty("user.home"); 
    File wd = new File(homedir); 
    Process pwd = Runtime.getRuntime().exec("pwd", null, wd); 
    Scanner scanner = new Scanner(pwd.getInputStream()); 
    while (scanner.hasNextLine()) { 
     System.out.println(scanner.nextLine()); 
    } 
} 
catch (Exception e) { 
    System.out.println(e.getMessage()); 
} 

如果您打算在運行像多個命令這個,我建議你按照上面的鏈接,並嘗試使用支持多個命令的其他方法之一。