我有一个像这样的简单类:
public class Dog {
public static void main(String[] args) {
System.out.println("DOG");
}
}
它被编译成Dog.class位于里面C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\Test\classes。我尝试使用 ProcessBuilder 运行它:
public static void main(String[] args) {
String pathName = "-cp \"C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\webapps\\Test\\classes" + "\" " + "Dog";
runCode(pathName);
}
public static void runCode(String name) {
System.out.println(name); //-cp "C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\Test\classes" Dog
ProcessBuilder processBuilder = new ProcessBuilder("java " + name);
processBuilder.redirectError(new File(Paths.get("C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\webapps\\JavaStudyRooms\\output.txt").toString()));
processBuilder.redirectInput();
try {
final Process process = processBuilder.start();
try {
final int exitStatus = process.waitFor();
if(exitStatus==0){
System.out.println("External class Started Successfully.");
System.exit(0); //or whatever suits
}else{
System.out.println("There was an error starting external class. Perhaps path issues. Use exit code "+exitStatus+" for details.");
System.out.println("Check also output file for additional details.");
System.exit(1);//whatever
}
} catch (InterruptedException ex) {
System.out.println("InterruptedException: "+ex.getMessage());
}
} catch (IOException ex) {
System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
}
System.out.println("Process Terminated.");
System.exit(0);
}
为什么会发生这种情况以及如何解决?
holdtom
相关分类