java执行cmd命令

	public static void main(String[] args) {
		try {
			exec(new String[]{
				"cmd.exe",
				"/C",
				"java"
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 运行cmd命令
	 */
	public static boolean exec(String[] cmdAry) throws Exception {
		Runtime rt = Runtime.getRuntime();
		Process proc = null;
		try {
			proc = rt.exec(cmdAry); 
			/* 
			 * Runtime的exec()方法类似线程,不会在cmd命令执行完成后再继续运行下面的代码,
			 * 所以导致可能cmd命令还没执行完毕,程序就运行到了Process的destroy()方法,因
			 * 此需要一个方法去等待cmd命令执行完毕后,再运行exec()之后的方法
			 */
			return waitForProcess(proc) > 0;
		} finally {
			if (proc != null) {
				proc.destroy();
				proc = null;
			}
		}
	}
	
	/**
	 * 得到cmd命令返回的信息数据流,该流的运行周期与cmd命令的实行时间相同
	 */
	public static int waitForProcess(Process proc) throws Exception {
		// cmd命令有返回正确的信息流,和错误信息流,不过不能绝对表示cmd命令是否执行正确
		BufferedReader in = null;
		BufferedReader err = null;
		String msg = null;
		int exitValue = -1;
		try {
			in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			while ((msg = in.readLine()) != null) {
				System.out.println(msg);
				if (1 != exitValue) {
					exitValue = 1;
				}
			}
			err = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
			while ((msg = err.readLine()) != null) {
				System.out.println(msg);
				if (0 != exitValue) {
					exitValue = 0;
				}
			}
			return exitValue;
			
		} finally {
			if (null != in) {
				in.close();
				in = null;
			}
			if (null != err) {
				err.close();
				err = null;
			}
		}
	}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值