Java,原因:java.io.IOException: error=2, No such file or directory

2022-01-23 00:00:00 command java
java.io.IOException: Cannot run program "yarn": error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at java.lang.Runtime.exec(Runtime.java:620)
    at java.lang.Runtime.exec(Runtime.java:450)
    at java.lang.Runtime.exec(Runtime.java:347)
    at com.Main.main(Main.java:32)

您好,我在使用 Java 执行命令时遇到了一个奇怪的问题.我使用以下代码运行命令,如果我运行 mkdir testFolder,程序运行成功,但如果我更改命令如 yarn -v然后发生错误.

Hi there, I have a weird problem when execute a command using Java. I used the following code to run a command, if I run mkdir testFolder, the program run successful, but if I changed the command like yarn -v then error happen.

try {
    Process process = Runtime.getRuntime().exec("yarn -v");//, null, new File("/Users/macos/Desktop/TestProj/"));
} catch (IOException ex) {
    ex.printStackTrace();
}

P/s:在调试模式下:IntelliJ 可以运行上面的代码,但 Netbeans 失败了.

P/s: In debug mode: IntelliJ could run above code, but Netbeans failed.

在生产模式下(jar 文件):IntelliJ 也失败了.

In production mode (jar file): IntelliJ failed too.

编辑 2:

  MACs-MacBook-Pro:~ macos$ which pwd
    /bin/pwd
    MACs-MacBook-Pro:~ macos$ which mkdir
    /bin/mkdir
    MACs-MacBook-Pro:~ macos$ which java
    /usr/bin/java
    MACs-MacBook-Pro:~ macos$ which yarn
    /usr/local/bin/yarn

我发现如果我运行 /bin/usr/bin 中的命令,代码运行正常(pwd、mkdir、java -version ...),但是yarn在/usr/local/bin/里,所以没用,我还不知道怎么解决.

I found that if I run a command that is in /bin or /usr/bin, the code run ok (pwd, mkdir, java -version ...), but yarn is in /usr/local/bin/, so it didn't work, and I still don't know how to fix.

推荐答案

终于找到答案了,因为我启动的进程和终端的进程不同,所以无法访问/usr/local/bin,有添加 -l 以登录用户身份运行命令.Runtime.getRuntime().exec(new String[]{"bash", "-l", "-c", cmd}, null, new File(f))

I finally found the answer, because the Process I start is different with the process of the terminal, so can't access /usr/local/bin, have to add -l to run the command as logged in user. Runtime.getRuntime().exec(new String[]{"bash", "-l", "-c", cmd}, null, new File(f))

相关文章