
如何用java实现调用shell
【代码】如何用java实现调用shell。
·
代码示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ShellCommandExecutor {
public static String executeCommand(String command) {
StringBuilder output = new StringBuilder();
try {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", command);
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new IOException("Command execution failed with exit code " + exitCode);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return output.toString();
}
public static void main(String[] args) {
String command = "ls -l"; // 你可以将要执行的Shell命令替换成你需要的命令
String result = executeCommand(command);
System.out.println("Command Output:\n" + result);
}
}
更多推荐
所有评论(0)