【问题标题】:having trouble running Linux commands in java在 Java 中运行 Linux 命令时遇到问题
【发布时间】:2014-10-25 19:03:30
【问题描述】:

为什么会出现以下错误:

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 再次出现...... 问题是什么?有什么想法吗?

谢谢:)

【问题讨论】:

  • 您需要一个解释器(shell)来运行 cd 命令。 cd 本身不是可执行程序。

标签: java linux command-line terminal


【解决方案1】:

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

您可能已经注意到,此代码仍然返回错误,因为使用波浪号作为对主目录的引用是 shell 的另一个好处。您可以将“~/”替换为主目录,或者在更可能未知的情况下,您可以使用以下代码获取目录:

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());
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2019-03-04
    相关资源
    最近更新 更多