java 封装一个调用不同的shell命令,返回一个字符转的方法
时间: 2024-03-09 21:47:57 浏览: 95
一个基于FFMPEG命令封装的简单java推流器.zip
可以使用Java中的ProcessBuilder类来调用不同的shell命令,并返回一个字符转。以下是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ShellCommandExecutor {
public static String executeCommand(String command) {
String output = "";
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command("bash", "-c", command);
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output += line + "\n";
}
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new RuntimeException("Command '" + command + "' returned non-zero exit status " + exitCode);
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
return output;
}
}
```
你只需要调用`executeCommand`方法并传入你想要执行的shell命令即可。例如,如果你想要执行`ls`命令并返回结果,你可以这样做:
```java
String output = ShellCommandExecutor.executeCommand("ls");
System.out.println(output);
```
这将在控制台输出`ls`命令的结果。
阅读全文