问题
这个问题在这里已有答案:
- 在单独的进程中执行Java应用程序9答案
有没有办法在Java应用程序中运行此命令行?
java -jar map.jar time.rel test.txt debug
我可以用命令运行它但我无法在Java中执行它。
#1 热门回答(158 赞)
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
#2 热门回答(46 赞)
你还可以像这样观看输出:
final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
不要忘记,如果你在Windows中运行,则需要在命令前放置"cmd / c"。
#3 热门回答(15 赞)
为了避免在标准输出和/或错误输出大量数据时阻止被调用进程,你必须使用Craigo提供的解决方案。另请注意,ProcessBuilder优于Runtime.getRuntime()。exec()。这有几个原因:它更好地标记参数,并且它还处理错误标准输出(另请参见here)。
ProcessBuilder builder = new ProcessBuilder("cmd", "arg1", ...);
builder.redirectErrorStream(true);
final Process process = builder.start();
// Watch the process
watch(process);
我使用新功能"watch"在新线程中收集这些数据。当被调用的进程结束时,该线程将在调用进程中完成。
private static void watch(final Process process) {
new Thread() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}