// 使用 Java 的 Runtime 类来执行系统命令
public class JavaRuntimeExample {
public static void main(String[] args) {
// 获取运行时对象
Runtime runtime = Runtime.getRuntime();
try {
// 执行系统命令,例如列出当前目录下的文件和文件夹(在 Unix/Linux/MacOS 中使用 "ls")
Process process = runtime.exec("ls");
// 获取命令输出流
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
// 读取并打印命令输出
String s;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// 等待命令执行完成
int exitCode = process.waitFor();
System.out.println("Exit Code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
Runtime runtime = Runtime.getRuntime(); 获取当前 Java 应用程序的运行时对象。runtime.exec("ls"); 使用 exec 方法执行系统命令。这里以 ls 命令为例,它会列出当前目录下的文件和文件夹(适用于 Unix/Linux/MacOS 系统)。对于 Windows 系统,可以使用 dir 命令。BufferedReader 和 InputStreamReader 来读取命令的输出,并逐行打印到控制台。process.waitFor(); 等待命令执行完毕,并返回退出状态码。IOException 和 InterruptedException 异常。这个示例展示了如何使用 Java 的 Runtime 类来执行外部命令并处理其输出。
上一篇:java生成uuid方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站