
Java提供了一个名为java.lang.Runtime的类,使用这个类可以与当前环境进行交互。
getRunTime() 此类的(静态)方法返回与当前应用程序关联的 Runtime 对象。
exec() 方法接受表示命令的字符串值在当前环境(系统)中执行一个进程并执行它。
因此,使用 Runtime 类执行外部应用程序 -
立即学习“Java免费学习笔记(深入)”;
通过将其路径作为字符串值传递给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 类的构造函数接受表示执行进程的命令的字符串类型的变量参数及其参数作为参数和构造一个对象。
此类的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中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号