Java, Caused by: java.io.IOException: error=2, No such file or directory(Java,原因:java.io.IOException: error=2, No such file or directory)
问题描述
您好,我在使用 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.
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:
我发现如果我运行 /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))
这篇关于Java,原因:java.io.IOException: error=2, No such file or directory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!