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.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))
这篇关于Java,原因:java.io.IOException: error=2, No such file or directory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java,原因:java.io.IOException: error=2, No such file or directory


基础教程推荐
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01