首页 文章资讯内容详情

如何在Java中执行Windows Media Player之类的外部程序?

2026-06-04 1 花语

使用运行时类

Java提供了一个名为java.lang.Runtime的类,使用该类可以与当前环境进行接口。

getRunTime()这个类的(静态)方法返回与当前应用程序相关联的运行时对象。

exec()方法接受表示在当前环境(系统)中执行进程的命令的String值并执行它。

因此,要使用Runtime类执行外部应用程序-

使用getRuntime()方法获取运行时对象。

通过将所需的路径作为String值传递给exec()方法来执行所需的过程。

例import java.io.IOException; public class Trail { public static void main(String args[]) throws IOException { Runtime run = Runtime.getRuntime(); System.out.println("Executing the external program . . . . . . . ."); String file = "C:\\Program Files\\Windows Media Player\\wmplayer.exe"; run.exec(file); } }输出结果System.out.println("Executing the external program . . . . . . . .

使用ProcessBuilder类

类似地,ProcessBuilder类的构造函数接受类型为string的变量参数,该变量参数表示执行流程的命令,并将其参数作为参数并构造对象。

此类的start()方法启动/执行当前ProcessBuilder中的进程。因此,要使用ProcessBuilder类运行外部程序-

通过传递命令以执行流程并将其参数作为构造函数的参数来实例化ProcessBuilder类。

通过在上面创建的对象上调用start()方法来执行该过程。

例import java.io.IOException; public class ExternalProcess { public static void main(String args[]) throws IOException { String command = "C:\\Program Files\\Windows Media Player\\wmplayer.exe"; String arg = "D:\\sample.mp3"; //Building a process ProcessBuilder builder = new ProcessBuilder(command, arg); System.out.println("Executing the external program . . . . . . . ."); //Starting the process builder.start(); } }输出结果Executing the external program . . . . . . . .