【Java】Java调用本机运行环境运行程序

    在window上用cmd,在Linux用终端时,都可以很方便的调用一些命令如ping。其实在java里也可以直接调用那些命令,并返回结果。Java中有Runtime类,运用此类就可以更本机的运行环境相连接,从而调用一些命令。其实这也是在Linux下c接口的一种方式。下面是我在window环境下写的一个ping的小Demo。
public class CJAVA {
	public static void execute() {
		String[] cmdArray = {"ping", "www.baidu.com"};
		//String[] cmdArray = {"ping", "13.13.13.131", "-t"};
		DataInputStream din = null;
		Process child = null;
		try {
			child = Runtime.getRuntime().exec(cmdArray);
			din = new DataInputStream(new BufferedInputStream(child.getInputStream()));
			int c;
			StringBuffer sb = new StringBuffer("");
			while(true) {
				c = din.read();
				if(c == -1) {break;}
				sb.append((char)c);
				System.out.print((char)c);
			}
			//System.out.println(sb.toString());
			child.waitFor();
		} catch (IOException e) {
		} catch (InterruptedException e) {
		} finally {
			try {
				if(din != null) {
					din.close();
				}
			
			} catch (IOException e) {
			}
			if(child.exitValue() != 0) {
				child.destroy();
			}
		}
	}
}

代码比较简单,大家有兴趣可以研究一下Process类。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zfpigpig

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值