java如何打开exe
使用 Runtime.getRuntime().exec()
Java 可以通过 Runtime.getRuntime().exec() 方法启动外部程序,包括 .exe 文件。该方法接受一个字符串参数,表示要执行的命令或程序路径。
示例代码:

try {
Process process = Runtime.getRuntime().exec("C:\\path\\to\\program.exe");
// 可选:等待进程结束
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
使用 ProcessBuilder
ProcessBuilder 提供了更灵活的方式来启动外部程序,支持设置工作目录、环境变量等。
示例代码:

try {
ProcessBuilder builder = new ProcessBuilder("C:\\path\\to\\program.exe");
builder.directory(new File("C:\\path\\to")); // 设置工作目录
Process process = builder.start();
// 可选:等待进程结束
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
处理命令行参数
如果 .exe 需要传递参数,可以通过以下方式实现:
// 使用 Runtime.exec()
Runtime.getRuntime().exec("C:\\path\\to\\program.exe arg1 arg2");
// 使用 ProcessBuilder
ProcessBuilder builder = new ProcessBuilder("C:\\path\\to\\program.exe", "arg1", "arg2");
注意事项
- 路径中的反斜杠 (
\) 需要转义为双反斜杠 (\\) 或使用正斜杠 (/)。 - 确保 Java 进程有足够的权限执行目标
.exe文件。 - 如果需要捕获程序输出或错误流,可以通过
Process.getInputStream()和Process.getErrorStream()处理。
示例:捕获输出流
try {
Process process = Runtime.getRuntime().exec("C:\\path\\to\\program.exe");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}






