Search code examples
javaprocessprocessbuilder

Could not run another java programs from ProcessBuilder?


TestClass.java

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestClass {
    public static void main(String[] args) throws IOException {
        System.out.println("inside");
        ProcessBuilder pb = new ProcessBuilder("java", "-cp", "", "test.OtherClass");
        Process p = pb.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append(System.getProperty("line.separator"));
        }
        String result = builder.toString();
        System.out.println(result);
    }
}

OtherClass.java

package test;

public class OtherClass {
    public static void main(String ar[]) {
        System.out.println("Hello Amit!");
    }
}

I am trying to run OtherClass from TestClass, but I am not able to do it. Running TestClass just prints "inside". I am not getting any exception and I am clueless right now. I am implementing ProcessBuilder for the first time.

NOTE: I was able to run simple program using ProcessBuilder. Also Can you tell what is meaning of -cp; I googled a lot but could not find its meaning.

EDIT:

I have updated code and now I am getting

inside
Error: Could not find or load main class test.OtherClass

Thanks!


Solution

  • Its likely to be the classpath. Assuming you have a directory called test, Have you tried something like:

    ProcessBuilder pb = new ProcessBuilder("java", "-cp", ".", "test.OtherClass");