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
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
