有没有办法在Java应用程序中运行此命令行?
java -jar map.jar time.rel test.txt debug
我可以使用命令运行它,但我无法在Java中执行它。
答案 0 :(得分:172)
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
答案 1 :(得分:47)
您还可以观看输出:
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"在你的命令面前。
答案 2 :(得分:17)
为了避免在标准输出和/或错误输出大量数据时阻止被调用进程,您必须使用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);
我使用新功能"观看"在新线程中收集此数据。当被调用的进程结束时,该线程将在调用进程中完成。
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();
}
答案 3 :(得分:8)
import java.io.*;
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
如果您遇到任何其他问题,请考虑以下问题,但我猜测上述内容对您有用:
答案 4 :(得分:7)
Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
答案 5 :(得分:4)
怎么样
public class CmdExec {
public static Scanner s = null;
public static void main(String[] args) throws InterruptedException, IOException {
s = new Scanner(System.in);
System.out.print("$ ");
String cmd = s.nextLine();
final Process p = Runtime.getRuntime().exec(cmd);
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();
}
}
答案 6 :(得分:3)
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
答案 7 :(得分:3)
您是否在Runtime类中尝试过exec命令?
Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")