简体   繁体   中英

Java, Caused by: 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)

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: In debug mode: IntelliJ could run above code, but Netbeans failed.

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

Edit 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

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.

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))

As error code 2 suggests you specified a path incorrectly. The error code corresponds to POSIX ENOENT and "No such file or directory" its char * strerror(int errno) representation.

To troubleshoot the problem by yourself you can read the manual page http://man7.org/linux/man-pages/man2/execve.2.html

The relevant section is:

ENOENT

The file filename or a script or ELF interpreter does not exist, or a shared library needed for the file or interpreter cannot be found.

To see with which particula path your process is strarted run java witj strace -f

In my case, I was using an ANT script that at some point called javac task with a fork=true attribute. Inspired by maphongba008 answer I deleted that fork, and so I stopped getting this same error.

这对我有用:

npm install -g yarn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM