How to make a class available for Runtime java command outside of package

485 views Asked by At

I am trying to run a Java program from another Java program where both programs are not in the same package in fact not even in the same project and to begin with I had found an answer on SO, here is the code:

    try {
            Process processCompile = Runtime.getRuntime().exec("javac Main.java");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Process processRun = null;
        try {
            processRun = Runtime.getRuntime().exec("java Main");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            printLines(" stdout:", processRun.getInputStream());
            printLines(" stderr:", processRun.getErrorStream());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Executing the following code gives me the following error:

Error: Could not find or load main class Main

Now I understand I have to somehow make Main.java available universally to run it from another program. I am not sure how to do this though.

I would really appreciate some help on this.

1

There are 1 answers

8
davidxxx On BEST ANSWER

I am trying to run a Java program from another Java program where both programs are not in the same package in fact not even in the same project and to begin with I had found an answer on SO, here is the code:

It the class is defined in a package you should specify it when you run the java command :

try {
        processRun = Runtime.getRuntime().exec("java Main");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Besides, if the class was defined in a package, you'd better to define it in a directory structure symmetric to the package. I said that since when you compile the class, you don't specify the path of the package of the Main.java file :

try {
            Process processCompile = Runtime.getRuntime().exec("javac Main.java");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }