简体   繁体   中英

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?

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))‌​; .

Where is the error in my code?

(You are launching the javaw executable, so that is not the problem. It is also not that your entry point method's signature is incorrect, because that would have given a different diagnostic.)

The problem is either that the class name is incorrect (eg if should be "come.pkg.Program"), or the pathname for the JAR file is incorrect.


Assuming that you have eliminated the possibility that the class name is incorrect, my guess is that you are trying to use a relative pathname for the JAR file, but there is some confusion over what the current directory is; ie the directory in which the pathname needs to be resolved. Try using an absolute pathname in the classpath parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM