我有一个像这样的简单类: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); }为什么会发生这种情况以及如何解决?
1 回答
holdtom
TA贡献1805条经验 获得超10个赞
ProcessBuilder 不使用整个命令行。它需要争论。
例如,您当前的代码正在寻找一个基本名称长度为 90 个字符的程序java -cp … Dog.exe。
您需要传递一个参数数组:
// Note the use of a String array, not a single String
public static void runCode(String... javaArgs) {
List<String> args = new ArrayList<>();
args.add("java");
Collections.addAll(args, javaArgs);
ProcessBuilder processBuilder = new ProcessBuilder(args);
这可以被调用为:
runCode(
"-cp",
"C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\webapps\\Test\\classes",
"Dog");
另外,不要只打印异常消息。消息本身很少有用。您通常想要打印整个堆栈跟踪,这样您将拥有所有信息并且您将确切地知道问题发生的位置:
} catch (IOException ex) {
ex.printStackTrace();
}
添加回答
举报
0/150
提交
取消