java如何使用runtime
如何使用 Java Runtime
Java 的 Runtime 类允许与应用程序的运行时环境交互,例如执行外部命令、获取内存信息或关闭 JVM。以下是常见用法:
获取 Runtime 实例
Runtime 是单例模式,通过静态方法 getRuntime() 获取实例:
Runtime runtime = Runtime.getRuntime();
执行外部命令
使用 exec() 方法执行系统命令,返回一个 Process 对象:
Process process = runtime.exec("notepad.exe");
如果需要传递参数,可以使用字符串数组:
String[] cmd = {"ping", "google.com"};
Process process = runtime.exec(cmd);
处理命令输出
通过 Process 对象可以获取命令的输入流、错误流和输出流:
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
获取 JVM 内存信息
Runtime 提供方法获取内存使用情况:
long freeMemory = runtime.freeMemory(); // 空闲内存(字节)
long totalMemory = runtime.totalMemory(); // 总分配内存(字节)
long maxMemory = runtime.maxMemory(); // JVM 最大可用内存(字节)
关闭 JVM
可以使用 halt() 或 exit() 方法终止 JVM:
runtime.exit(0); // 正常退出,状态码 0
runtime.halt(1); // 强制终止,状态码 1
注意事项
exec()方法可能抛出IOException,需处理异常。- 执行长时间运行的命令时,建议使用
Process.waitFor()等待完成。 - 注意命令注入风险,避免直接拼接用户输入到命令中。
示例代码
以下是一个完整的示例,展示如何执行命令并读取输出:

public class RuntimeExample {
public static void main(String[] args) throws IOException, InterruptedException {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd /c dir"); // Windows 下列出目录
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
}
}






