Search code examples
javaprocessprocessbuilder

Java ProcessBuilder


I'm having problems using ProcessBuilder to run a class in my project. My code:

public class Main {
    public static void main(String[] args) {
        try {
            String pathToJar = Main.class.getProtectionDomain().getCodeSource()
                    .getLocation().toURI().getPath();
            ArrayList<String> params = new ArrayList<String>();    
            params.add("javaw");
            params.add("-classpath");
            params.add(pathToJar);
            params.add("Program");
            ProcessBuilder pb = new ProcessBuilder(params);
            Process process = pb.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Program is in same project (same bin folder) and works fine if ran directly but this way I get the error "Could not find the main class: Program". Where is the error in my code?

Thanks in advance.

[EDIT] I came to the conclution that is some code on my Program class giving error. Basicly only runs with "clean" main. At eclipse, Program class is importing some libraries that are inside a jar file. Don't I need to reference it in ProcessBuilder? If so, how?


Solution

  • In response to your edit:

    You can add the current path by switching params.add(pathToJar); with params.add(System.getProperty("java.class.path").concat(";").concat(pathToJar))‌​;.