How to add a timeout value when using Java's Runtime.exec()?

前端 未结 17 1803
长发绾君心
长发绾君心 2020-11-27 12:08

I have a method I am using to execute a command on the local host. I\'d like to add a timeout parameter to the method so that if the command being called doesn\'t finish in

17条回答
  •  孤城傲影
    2020-11-27 12:39

    Apache Commons Exec can help you to do it.

    See http://commons.apache.org/proper/commons-exec/tutorial.html

    String line = "your command line";
    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    int exitValue = executor.execute(cmdLine);
    System.out.println(exitValue);
    System.out.println(outputStream.toString());
    

提交回复
热议问题