java 运行命令行指令并获取输出信息

1.代码

public static String runCmd(String cmdpath, String cmd) {
		log.info(cmd);
		String result="";
		File dir = new File(cmdpath);
		try {
			Process ps = Runtime.getRuntime().exec(cmd, null, dir);
	
			BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream(), Charset.forName("GBK")));
			String line = null;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
				result+=line+"\n";
			}

			br.close();
			System.out.println("close ... ");
			ps.waitFor();
			System.out.println("wait over ...");
			
			return result;
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("child thread donn");
		return null;
	}

2.测试

public static void main(String args[]){
		runCmd("C:\\","ping www.baidu.com");
	}

3.结果

11-28 10:11:36.232 INFO  [com.knife.doc.Utils.CmdUtils] - ping www.baidu.com

正在 Ping www.a.shifen.com [115.239.210.27] 具有 32 字节的数据:
来自 115.239.210.27 的回复: 字节=32 时间=3ms TTL=54
来自 115.239.210.27 的回复: 字节=32 时间=6ms TTL=54
来自 115.239.210.27 的回复: 字节=32 时间=4ms TTL=54
来自 115.239.210.27 的回复: 字节=32 时间=4ms TTL=54

115.239.210.27 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 3ms,最长 = 6ms,平均 = 4ms
close ... 
wait over ...

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值