问题描述
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.
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(新字符串[] {"bash",-l",-c",cmd},空,新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))
这篇关于Java,原因:java.io.IOException:错误= 2,没有这样的文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!