我有一个方法,我用来在本地主机上执行命令.我想在方法中添加一个超时参数,这样如果被调用的命令没有在合理的时间内完成,那么该方法将返回错误代码.这是迄今为止的样子,没有超时的能力:
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();
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以建议我实现超时参数的好方法吗?