代码如下:
/**
* 功能描述: 执行多条命令
*
* @param commandList 命令列表
* @return {@link List }<{@link String }>
* @author song
* @date 2024/02/27 17:39:58
*/
public List<String> lineExecUtil(List<String> commandList) {
try {
// 创建一个ProcessBuilder对象,指定命令和参数
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe");
//linux
// ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash");
processBuilder.redirectErrorStream(true); // 将错误流重定向到输出流
// 启动进程
Process process = processBuilder.start();
// 获取进程的输入流和输出流
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), CharsetUtil.GBK));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(process.getOutputStream(), CharsetUtil.GBK), true);
// 发送多个输入到命令行
for (String s : commandList) {
writer.println(s);
}
// 读取命令行的输出
List<String> result = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
result.add(line);
}
// 等待进程执行结束
int exitCode = process.waitFor();
System.out.println("进程执行完毕,退出码:" + exitCode);
// 关闭流
reader.close();
writer.close();
return result;
} catch (IOException | InterruptedException e) {
e.printStackTrace();
return null;
}
}
使用示例:
public void execCommandList() {
String s1 = "dir";
String s2 = "ipconfig";
String s3 = "ping www.baidu.com";
String s4 = "exit";
List<String> commandList = new ArrayList<>();
commandList.add(s1);
commandList.add(s2);
commandList.add(s3);
commandList.add(s4);
List<String> result = lineExecUtil(commandList);
for (String s : result) {
System.out.println(s);
}
}
输出打印:
无线局域网适配器 WLAN:
连接特定的 DNS 后缀 . . . . . . . :
IPv4 地址 . . . . . . . . . . . . : 192.168.14.233
子网掩码 . . . . . . . . . . . . : 255.255.255.0
默认网关. . . . . . . . . . . . . : 192.168.14.139
D:\workspace\**>ping www.baidu.com
正在 Ping www.a.shifen.com [39.156.66.14] 具有 32 字节的数据:
来自 39.156.66.14 的回复: 字节=32 时间=35ms TTL=49
来自 39.156.66.14 的回复: 字节=32 时间=31ms TTL=49
来自 39.156.66.14 的回复: 字节=32 时间=41ms TTL=49
来自 39.156.66.14 的回复: 字节=32 时间=77ms TTL=49
39.156.66.14 的 Ping 统计信息:
数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 31ms,最长 = 77ms,平均 = 46ms
D:\workspace\**>exit