我正在开发一个java程序,我必须使用进程构建器调用另一个java程序,因为它使用单独的JRE。
这是批处理程序,它调用此程序并正常工作:
cd C:\apps\Project_name\bin\
C:\Progra~1\Java\jre1.6.0_03\bin\java -Xms512m -Xmx1024m
-cp ../lib/spring-1.2.2.jar;../lib/log4j-1.2.8.jar;../lib/commons-logging-1.0.4.jar;../lib/wrapper.jar
com.project.main.MainProgramLauncher arg1 arg2
现在我宣布我的代码是这样的:
ProcessBuilder builder = new ProcessBuilder(
"java",
"-Xms512m",
"-Xmx1024m",
"-cp ../lib/spring-1.2.2.jar;../lib/log4j-1.2.8.jar;"+
"../lib/commons-logging-1.0.4.jar;../lib/wrapper.jar",
"com.project.main.MainProgramLauncher arg1 arg2 ...argN"
);
Map<String, String> environment = builder.environment();
environment.put("path", ";"); // Clearing the path variable;
environment.put("path", java_bin_location+";");
Process javap = builder.start();
InputStreamReader tempReader = new InputStreamReader(
new BufferedInputStream(javap.getInputStream())
);
BufferedReader reader = new BufferedReader(tempReader);
while (true) {
String line = reader.readLine();
if (line == null)
break;
System.out.println(line);
}
但它没有按照应有的方式执行。该程序立即崩溃。有什么不同我应该做的吗?请建议。
答案 0 :(得分:1)
我猜你应该让你的类名和参数变成不同的字符串。而不是:
"java",
"-Xms512m",
"-Xmx1024m",
"-cp ../lib/spring-1.2.2.jar;../lib/log4j-1.2.8.jar;"+
"../lib/commons-logging-1.0.4.jar;../lib/wrapper.jar",
"com.project.main.MainProgramLauncher arg1 arg2 ...argN"
应该是
"java",
"-Xms512m",
"-Xmx1024m",
"-cp",
"../lib/spring-1.2.2.jar;../lib/log4j-1.2.8.jar;"+
"../lib/commons-logging-1.0.4.jar;../lib/wrapper.jar",
"com.project.main.MainProgramLauncher",
"arg1",
"arg2",
...
"argN"
另一个值得注意的事情是您使用完整路径名称来调用java.exe
,而不是在使用ProcessBuilder
时。
您可能还想阅读错误流(或调用redirectErrorStream(true)
- 参数很重要(!))。