java - 在 java 中运行 Linux 命令时遇到问题

标签 java linux command-line terminal

为什么会出现以下错误:

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

谢谢:)

最佳答案

如前所述,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());
}

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

关于java - 在 java 中运行 Linux 命令时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25607726/

相关文章:

regex - 如何使用 .SH 文件脚本替换文本文件中的文本?

android - 无法在 Linux (Ubuntu) 中启动 SDK 管理器

c# - C# 中的网络 COPY Cmds - 找不到文件?

linux - 在 linux 中,如何在 gdb 中找到哪个线程处于挂起状态?

javascript - WebPack无法在本地项目中通过命令执行

java - 在 Eclipse RCP 应用程序中捕获终止信号

java - 如何限制Spring Roo中的menu.jspx对其他用户的实体执行CRUD操作

java - 更改了 build.gradle 现在无法安装应用程序删除失败内部错误

JavaFX ImageView : Can I retrieve the scaled image size when preserveRatio = true?

java - 将 JSF 应用程序迁移到 JavaFX