PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

WBOY
WBOY 转载
2023-09-04 09:25:02 864浏览

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

使用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 . . . . . . . .

以上就是如何在Java中执行外部程序,例如Windows Media Player?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除