2

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?

3
  • Does /home/local/prasanth-8508 definitely exist, and do you have permission to access it? Commented Jul 4, 2019 at 10:27
  • Yes Micheal, that directory exists. Otherwise I would've got a file no such file error. And I have the permission to access it too. Commented Jul 4, 2019 at 10:59
  • That's incorrect - you would have got exactly the error you specified if the directory didn't exist in this case (and depending on your platform, a possible qualifier after that exception to state that the directory was invalid too.) Checking that java is on your path would be my next port of call. Commented Jul 4, 2019 at 13:36

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

I don't run any jar files. I want to run a class file. And yes, by specifying the absolute path to java, it works. But do you have any idea why it is not working if I give only 'java' instead of the absolute/path/to/java?
It may possible that you need to set up the environment variable PATH for java bin directory and CLASSPATH for java lib directory in your system without that you need to specify the absolute path of java.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.