Java运行可执行文件
在Java编程中,当要执行一个本地机上的可执行文件是,可以使用java.lang包中Runtime类。
首先,使用Runtime类声明一个对象,如:Runtimeec ;
然后,使用该类的静态getRuntime()方法创建这个对象:ec = Runtime.getRuntime( ) ;
ec便可以调用exec(String command )方法打开本地机上的可执行文件或者执行一个操作了。
示例如下:
import java.io.File;
public class RuntimeDemo {
public staticvoidmain(String[] args){
try{
Runtime ec=Runtime.getRuntime();
//执行javac,编译java文件
ec.exec("javac RuntimeDemo.java");
//执行java程序,运行java文件
ec.exec("java RuntimeDemo");
//获取记事本信息放入file对象
File file=new File("C:/windows","notepad.exe");
//获取记事本的路径,执行记事本程序
ec.exec(file.getAbsolutePath());
}catch(Exception e){
e.printStackTrace();
}
}
}