您好,欢迎访问一九零五行业门户网

如何在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?的详细内容。
其它类似信息

推荐信息