阅读量:2
是的,Java的Runtime.getRuntime().exec()方法可以用于执行外部程序。这个方法允许你在Java应用程序中启动一个新的进程并执行外部命令或程序。以下是一个简单的示例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteExternalProgram {
public static void main(String[] args) {
try {
// 要执行的外部程序,例如notepad.exe
String command = "notepad.exe";
// 使用Runtime.getRuntime().exec()方法执行外部程序
Process process = Runtime.getRuntime().exec(command);
// 读取外部程序的输出
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("外部程序已执行完毕,退出码: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个示例中,我们使用Runtime.getRuntime().exec()方法执行了notepad.exe程序,并读取了它的输出。请注意,这个示例仅适用于Windows操作系统,因为notepad.exe是Windows特有的程序。对于其他操作系统,你需要将命令更改为相应的程序。
以上就是关于“java exec 能否执行外部程序”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm