`
uule
  • 浏览: 6304544 次
  • 性别: Icon_minigender_1
  • 来自: 一片神奇的土地
社区版块
存档分类
最新评论

JAVA执行DOS命令

 
阅读更多
/**
	 * @param cmd ant命令
	 * 
	 * @return 执行日志
	 * 
	 * @exception 执行有错误会抛出AntExecException
	 */
	public static String execute(String[] cmd){
		// 标准输出
		InputStream standardInput = null;
		BufferedReader standardReader = null;
		// 错误输出
		InputStream errInput = null;
		BufferedReader errReader = null;
		
		StringBuilder standardMsg = new StringBuilder();
		StringBuilder errMsg = new StringBuilder();
		
		Process process = null;
		try {
			// 执行ant
			process = Runtime.getRuntime().exec(cmd);
			// 读取标准输入流
			standardInput = process.getInputStream();
			if(standardInput != null){
				standardReader = new BufferedReader(new InputStreamReader(standardInput));
				String line = standardReader.readLine();
				while (null != line) {
					standardMsg.append(line).append("\n");
					line = standardReader.readLine();
				}
			}

			// 检查错误流是否有信息,如果有,则说明执行失败
			errInput = process.getErrorStream();
			if(errInput != null){
				errReader = new BufferedReader(new InputStreamReader(errInput));
				String errLine = errReader.readLine();
				while (null != errLine) {
					errMsg.append(errLine).append("\n");
					errLine = errReader.readLine();
				}
				if(errMsg.length() > 0){
					throw new AntExecException(standardMsg.append(errMsg).toString());
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new AntExecException(standardMsg.append(errMsg).toString());
		} finally {
			// 销毁进程对象,否则可能引起资源不能释放问题,出现Too many open files错误
			if (process != null) {
				process.destroy();
			}
			if (null != standardReader) {
				try {
					standardReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != errReader) {
				try {
					standardReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		logger.debug("executeAnt end...");
		return standardMsg.toString();
	}

 

public class AntExecException extends RuntimeException {

	private static final long serialVersionUID = -3708533380275512493L;

	public AntExecException() {
		super();
	}

	public AntExecException(String message, Throwable cause) {
		super(message, cause);
	}

	public AntExecException(String message) {
		super(message);
	}

	public AntExecException(Throwable cause) {
		super(cause);
	}

}

 

..

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics