使用Runtime类
Java提供了一个名为java.lang.Runtime的类,使用这个类可以与当前环境进行交互。
getRunTime() 此类的(静态)方法返回与当前应用程序关联的 Runtime 对象。
exec() 方法接受表示命令的字符串值在当前环境(系统)中执行一个进程并执行它。
因此,使用 Runtime 类执行外部应用程序 -
示例
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 类运行外部程序 -
示例
实时演示
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?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。