如何在 Java 中执行外部程序,如 Windows Media Player?

javaobject oriented programmingprogramming更新于 2024/2/14 5:32:17

使用 Runtime 类

Java 提供了一个名为 java.lang.Runtime 的类,使用此类可以与当前环境交互。

此类的 getRunTime()(静态)方法返回与当前应用程序关联的 Runtime 对象。

exec() 方法接受一个字符串值,该值表示在当前环境(系统)中执行进程的命令并执行它。

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

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

  • 通过将所需进程的路径作为字符串值传递给 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 类的构造函数接受一个字符串类型的变量参数,该变量参数表示执行进程的命令及其参数作为参数并构造一个对象。

此类的 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 . . . . . . . .

相关文章


有用资源