1 序言
- 实现自动化程序、跨环境调用的重要途径
2 源码示例
package test.java;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @author johnny-zen
* @version v1.0
* @create-time 2023/8/25 11:38
* @description ...
* @refrence-doc
* [1] 如何在 Java 中运行命令行 - 火焰兔 - https://www.zadmei.com/rhzjzyxm.html
* @gpt-promt
*/
public class ExecuteCommandTest {
@Test
public void processTest(){
String command = "jps -l";// jps -l / java -verbose
try {
// 创建一个 Runtime 实例
Runtime runtime = Runtime.getRuntime();
// 执行命令行命令
Process process = runtime.exec(command);
// 获取命令行输出结果
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待命令行执行完毕
int exitCode = process.waitFor();
System.out.println("finished to execute the command, and the exit code : " + exitCode);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void processBuilderTest(){
try {
// 指定要执行的命令或可执行文件及其参数
List<String> command = Arrays.asList("ping","www.baidu.com");
//List<String> command = Arrays.asList("cmd.exe", "/c", "dir");
// 创建一个 ProcessBuilder 实例
ProcessBuilder processBuilder = new ProcessBuilder(command); //new ProcessBuilder("dir", "-l");
// 设置工作目录(可选)
//String workingDirectory = "C:\\Users\\408675\\Desktop";
//processBuilder.directory(new File(workingDirectory));
// 启动进程
Process process = processBuilder.start();
// 获取命令行输出结果 (可选)
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));// Windows CMD 默认以 GBK 字符集 编码文本
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 获取环境信息 (可选)
// eg: <key: JAVA_HOME, value: D:\Program\Java\jdk1.8.0_261> ...
//Map<String, String> environment = processBuilder.environment();
//environment.entrySet().forEach(varEntry -> {
// System.out.println(String.format("<key: %s, value: %s>", varEntry.getKey(), varEntry.getValue()));
//});
// 获取命令行输出 | 等待外部进程结束
int exitValue = process.waitFor();
System.out.println("finished to execute the command, and the exit code : " + exitValue);
// 关闭进程
process.destroy();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
- output
processTest()
9984 org/netbeans/Main
22180 org.jetbrains.jps.cmdline.Launcher
22244 com.intellij.rt.junit.JUnitStarter
31268 sun.tools.jps.Jps
18424 D:\Program\DBeaver-23-0-4\dbeaver\plugins\org.eclipse.equinox.launcher_1.6.400.v20210924-0641.jar
27368 org.jetbrains.jps.cmdline.Launcher
11788 cn.seres.bd.datasource.biz.DataSourceApplication
6604 org.jetbrains.idea.maven.server.RemoteMavenServer36
finished to execute the command, and the exit code : 0
processBuilderTest()
D:\Program\Java\jdk1.8.0_261\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\Program\IDEA\IDEA_COMMUNITY 2022.2\lib\idea_rt.jar=61044:D:\Program\IDEA\IDEA_COMMUNITY 2022.2\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\xxxx\AppData\Local\Temp\classpath2097328303.jar com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 test.java.ExecuteCommandTest,processBuilderTest
正在 Ping www.baidu.com [120.232.145.144] 具有 32 字节的数据:
来自 120.232.145.144 的回复: 字节=32 时间=44ms TTL=48
来自 120.232.145.144 的回复: 字节=32 时间=44ms TTL=48
来自 120.232.145.144 的回复: 字节=32 时间=45ms TTL=48
来自 120.232.145.144 的回复: 字节=32 时间=44ms TTL=48
120.232.145.144 的 Ping 统计信息:
数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 44ms,最长 = 45ms,平均 = 44ms
<key: USERDOMAIN_ROAMINGPROFILE, value: XXXX>
...