有运行Linux在Java命令麻烦

问题描述:

为什么我收到以下错误:有运行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

正如阿加德所说,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()); 
} 

如果您打算在运行像多个命令这个,我建议你按照上面的链接,并尝试使用支持多个命令的其他方法之一。