在 Java 中运行命令行

2022-08-31 08:06:07

有没有办法在 Java 应用程序中运行此命令行?

java -jar map.jar time.rel test.txt debug

我可以用命令运行它,但我不能在Java中做到这一点。


答案 1
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

您还可以像这样观看输出:

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

编辑:对于奖励积分,您还可以使用将输入传递给程序:ProcessBuilder

String[] command = new String[] {
        "choice",
        "/C",
        "YN",
        "/M",
        "\"Press Y if you're cool\""
};
String inputLine = "Y";

ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

writer.write(inputLine);
writer.newLine();
writer.close();

String line;

while ((line = reader.readLine()) != null) {
    System.out.println(line);
}

这将运行 windows 命令并使用 .因此,输出将为:choice /C YN /M "Press Y if you're cool"Y

Press Y if you're cool [Y,N]?Y

推荐