在 Java 中运行命令行
Sheeraz Gul
2023年1月30日
2022年4月27日
本文演示了如何在 Java 中运行命令并显示输出。
在 Java 中使用 Runtime.getRuntime().exec()
运行命令
Runtime.getRuntime().exec()
是 Java 运行命令的内置功能。
例子:
import java.io.*;
public class cmd_class {
public static void main(String[] args) throws Exception {
Process runtime = Runtime.getRuntime().exec("ping www.delftstack.com");
Show_Output(runtime);
}
public static void Show_Output(Process process) throws IOException {
BufferedReader output_reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = "";
while ((output = output_reader.readLine()) != null) {
System.out.println(output);
}
}
}
上面的代码通过 Runtime.getRuntime().exec()
运行命令,并使用用户定义的函数 Show_Output()
显示输出。
输出:
Pinging www.delftstack.com [3.66.136.156] with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Ping statistics for 3.66.136.156:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
输出将与命令行中的相同。ping www.delftstack.com
的请求超时。
在 Java 中使用 Process Builder 运行命令
Process Builder 库还用于在 Java 中运行命令。
例子:
import java.io.*;
public class cmd_class {
public static void main(String[] args) throws Exception {
ProcessBuilder build_test = new ProcessBuilder(
"cmd.exe", "/c", "java -version");
build_test.redirectErrorStream(true);
Process p = build_test.start();
Show_Results(p);
}
public static void Show_Results(Process p) throws IOException {
BufferedReader output_reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String output = "";
while ((output = output_reader.readLine()) != null) {
System.out.println(output);
}
}
}
上面的代码使用 Process Builder 功能运行命令 java -version
。
输出:
java version "17.0.2" 2022-01-18 LTS
Java(TM) SE Runtime Environment (build 17.0.2+8-LTS-86)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.2+8-LTS-86, mixed mode, sharing)
进程构建器打开 cmd
然后运行给定的命令。
Author: Sheeraz Gul
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook