转贴请注明出处:
http://blog.youkuaiyun.com/froole
一个简单的兼容timeout的Java执行外部命令的小程序。
单线程,易于测试。
应该可以满足大多数后台程序的需要。
要注意的事,超过timeout时间之后,根据系统的不同,有可能无法马上强制停止process,这个时候只能用waitFor判断程序是否结束。
一个简单的兼容timeout的Java执行外部命令的小程序。
单线程,易于测试。
应该可以满足大多数后台程序的需要。
要注意的事,超过timeout时间之后,根据系统的不同,有可能无法马上强制停止process,这个时候只能用waitFor判断程序是否结束。
- /**
- * 让Java执行外部命令兼容timeout<br>
- * timeout誤差<=0.5秒
- *
- * @version 1.0
- * @author 郝春利
- */
- public class CommandExec {
- /**
- * 计算间隔时间
- */
- private static final int TIME_MARGIN = 500;
- /**
- * 命令
- */
- private String command;
- /**
- * timeout。単位:milli秒
- */
- private int timeout;
- /**
- *
- *
- * @param command
- * @param timeout
- */
- public CommandExec(String command, Integer timeout) {
- this.command = command;
- this.timeout = timeout;
- }
- /**
- *
- * 执行命令<br>
- *
- * @param options
- * 命令的参数
- * @param dir
- * 作业目录
- * @return 返回执行结果的状态。
- * @throws IOException
- * I/O异常
- */
- public Process exec(String[] options, File dir) throws IOException {
- String[] commands = null;
- if (options == null) {
- commands = new String[] { command };
- } else {
- commands = new String[options.length + 1];
- commands[0] = command;
- for (int i = 0; i < options.length; i++) {
- commands[i + 1] = options[i];
- }
- }
- Process process = Runtime.getRuntime().exec(commands, null, dir);
- long limitTime = timeout + System.currentTimeMillis();
- Integer status = null;
- do {
- try {
- status = process.exitValue();
- break;
- } catch (IllegalThreadStateException e) {
- try {
- Thread.sleep(TIME_MARGIN);
- } catch (InterruptedException we) {
- throw new RuntimeException("err.fail.wait");
- }
- }
- } while (System.currentTimeMillis() < limitTime);
- if (status == null) {
- process.destroy();
- try {
- status = process.exitValue();
- } catch (IllegalThreadStateException e) {
- }
- }
- return process;
- }
- public ByteArrayOutputStream getOutputStream(InputStream input) throws IOException {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- for (int ch = 0; (ch = input.read()) != -1;) {
- out.write(ch);
- }
- return out;
- }
- }