问题
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?
回答1:
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));
.
回答2:
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 (e.g. 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; i.e. the directory in which the pathname needs to be resolved. Try using an absolute pathname in the classpath parameter.
来源:https://stackoverflow.com/questions/10568840/java-processbuilder