java执行shell命令并返回结果
时间: 2023-09-22 18:10:47 浏览: 95
可以使用Java中的`Runtime`类来执行Shell命令并返回结果。以下是一个简单的示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ShellCommand {
public static void main(String[] args) {
String command = "ls -l"; // 要执行的Shell命令
try {
Process process = Runtime.getRuntime().exec(command);
// 读取Shell命令的输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待Shell命令执行完毕
int exitCode = process.waitFor();
// 输出Shell命令的退出码
System.out.println("Exit code: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上代码将执行`ls -l`命令并输出其结果。你可以将`command`变量设置为你想要执行的任何Shell命令。