简体   繁体   中英

Runtime.exec won't run javac, but command line will

In my program, I create a.java file and then compile it. The command I use looks like this:

javac -classpath [path to main directory]\my.jar -d [path to main directory]\bin [path to main directory]\src\pkg1\MyClass.java

This is called with the following code:

Runtime runtime = Runtime.getRuntime()
runtime.exec(command)

However, when I run it by clicking "Run" in Eclipse, I get the following error:

java.io.IOException: Cannot run program "javac": CreateProcess error=2, 
    The system cannot find the file specified

Now, I know what this means: I haven't installed Java correctly, and my path variable needs to include the JDK. However, the problem with that simple hypothesis is that it works perfectly fine when I use the exact same command from the command line (obviously not with runtime.exec() , but still). I know it's not a fault with my Java installation or with the command itself, because otherwise it wouldn't work from the command line, so what's left and how do I fix it?

The problem

You are asking the JVM to run a command named "javac", but it fails with an error:

java.io.IOException: Cannot run program "javac": CreateProcess error=2,
The system cannot find the file specified

Explanation

The JVM does not know where to find "javac". Whether or not you are able to run "javac" yourself is separate from whether the JVM can also run that command.

Reproducing the behavior

Here's a simple program to reproduce the behavior – it tries to run "test.sh":

String command = "test.sh";
Process process = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println("command: [" + command + "] -- " + "output: [" + br.readLine() + "]");

Running that code will throw an exception because the JVM doesn't know where to find "test.sh":

java.io.IOException: Cannot run program "test.sh": error=2, No such file or directory

Solution

I do in fact have "test.sh" located on my computer, but I didn't specify the full path earlier ("/var/tmp") in the Java program. The script is pretty simple, it just runs the "date" command:

% cat /var/tmp/test.sh
#!/bin/sh
date "+%Y-%m-%d"

% /var/tmp/test.sh 
2022-08-05

Editing the command so that it's using an absolute path to "test.sh" works fine:

String command = "/var/tmp/test.sh";

command: [/var/tmp/test.sh] -- output: [2022-08-05]

Example: same for javac

This works fine for "javac", too – here's the output from command "/usr/bin/javac -version" :

command: [/usr/bin/javac -version] -- output: [javac 18.0.1.1]

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