在一个终端(cmd或/bin/bash)中执行多条命令的工具类

代码如下:

	/**
	 * 功能描述: 执行多条命令
	 *
	 * @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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值