使用Java的 Runtime.exec()时如何添加超时值?
我有一个方法用于在本地主机上执行命令。我想向该方法添加一个超时参数,以便在被调用的命令未在合理的时间内完成时,该方法将返回错误代码。以下是到目前为止的外观,没有超时功能:
public static int executeCommandLine(final String commandLine,
final boolean printOutput,
final boolean printError)
throws IOException, InterruptedException
{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(commandLine);
if (printOutput)
{
BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println("Output: " + outputReader.readLine());
}
if (printError)
{
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
System.out.println("Error: " + errorReader.readLine());
}
return process.waitFor();
}
任何人都可以为我提供一种实现超时参数的好方法吗?