用java写一个方法,使用ProcessBuilder调用linux命令,要求处理好输出和报错信息,注意超时问题
时间: 2024-03-08 08:49:42 浏览: 209
Java如何基于ProcessBuilder类调用外部程序
好的,下面是一个使用ProcessBuilder调用Linux命令并处理输出和报错信息的Java方法:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
public class LinuxCommandExecutor {
public static String executeCommand(List<String> command, int timeoutInSeconds) throws Exception {
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stderrReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
long startTime = System.currentTimeMillis();
while (isAlive(process)) {
readStream(stdoutReader, output);
readStream(stderrReader, error);
if (System.currentTimeMillis() - startTime >= timeoutInSeconds * 1000) {
process.destroy();
throw new Exception("Command timed out after " + timeoutInSeconds + " seconds");
}
}
readStream(stdoutReader, output);
readStream(stderrReader, error);
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new Exception("Command exited with non-zero exit code: " + exitCode + "\nError: " + error.toString());
}
return output.toString();
}
private static void readStream(BufferedReader reader, StringBuilder output) throws IOException {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
}
private static boolean isAlive(Process process) {
try {
process.exitValue();
return false;
} catch (IllegalThreadStateException e) {
return true;
}
}
}
```
这个方法接收一个命令列表和一个超时时间(以秒为单位),执行该命令,并返回输出结果。如果命令返回非零退出码,则会抛出异常。如果命令在超时时间内没有完成,则会抛出超时异常。
使用示例:
```java
List<String> command = List.of("ls", "-l");
String output = LinuxCommandExecutor.executeCommand(command, 10);
System.out.println(output);
```
这个例子执行ls -l命令,并将结果输出到控制台。如果命令执行时间超过10秒,则会抛出超时异常。
阅读全文