如何在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 . . . . . . . .
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP