I am trying to run a java class file from another java program.
This is my program:
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
public class RunJava {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("java","HelloWorld");
pb.directory(new File("/home/local/prasanth-8508"));
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
pb.start();
}
}
After running this program I get the following error:
Exception in thread "main" java.io.IOException: Cannot run program "java"
But when I run any java commands from my terminal, they work absolutely fine.
Another thing I found is, when I run the command: echo $PATH
in my terminal and using the ProcessBuilder (ProcessBuilder pb = new ProcessBuilder("bash","-c","echo $PATH");
), they are showing different outputs. i.e The path to jdk/bin is not displayed in the ProcessBuilder command.
How can I solve this issue?
Yes, As @MichaelBerry said it is possible that you may not have permission to access it but other then that also I want to include,
Here you have started with very good ProcessBuilder you just need to modify small things like parameter -jar
in the constructor of processBuilder.
I've posted below sample code which may help you to understand how it will work.
ProcessBuilder pb = new ProcessBuilder("/path/to/java", "-jar", "your.jar");
pb.directory(new File("preferred/working/directory"));
Process p = pb.start();