我按照这样运行程序:
Process process;
try {
process = new ProcessBuilder("java", "-jar", "test.jar", "1", "20").start();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
我调用的程序使用标准输出System.out.println("Hello!");
但是,调用程序什么都没有回来。我使用ProcessBuilder()错了吗?谢谢!
答案 0 :(得分:1)
如果没有约束来启动另一个JVM(例如:在test.jar中使用System.exit()),则可以在当前JVM中加载并运行test.jar
。
以下代码段显示了原则。
File file = new File("/tmp/test.jar");
URLClassLoader loader = new URLClassLoader(
new URL[]{file.toURI().toURL()}
);
String className = new JarFile(file)
.getManifest()
.getMainAttributes()
.getValue(Attributes.Name.MAIN_CLASS);
Method main = loader
.loadClass(className)
.getDeclaredMethod("main", String[].class);
Object arg = new String[]{"1", "20"};
try {
main.invoke(null, arg);
} catch (Exception e) {
// do appropriate exception handling here
e.printStackTrace(System.err);
}