java使用Runtime和Process类执行外部程序,runtimeprocess,要在java程序中执行外
分享于 点击 16497 次 点评:76
java使用Runtime和Process类执行外部程序,runtimeprocess,要在java程序中执行外
要在java程序中执行外部程序,需要使用Runtime类的exec()方法,该方法返回Process类的实例。
在下面的例子中我们执行Notepad.exe,写字板是没有输出的,但是在有些情况我们需要获得程序执行的输出结果。
Process类的getInputStream()方法可以用来读输出数据。
waitFor()方法保证在外部进程执行完毕之前java程序不会退出。
如下是实例代码:
import java.io.DataInputStream;import java.io.IOException;/** * * @author byrx.net */public class Main { /** * This method executes an external program (Notepad.exe) * and waits for it to finish before exiting. */ public void executeExternalProgram() { try { //Get the reference to the Runtime instance Runtime runtime = Runtime.getRuntime(); //Run the external program and receive a reference to the process Process proc = runtime.exec("notepad.exe C:/test.txt"); //Read output data from the process while it has more DataInputStream bis = new DataInputStream(proc.getInputStream()); int _byte; while ((_byte = bis.read()) != -1) System.out.print((char)_byte); //Wait for the process to finish proc.waitFor(); } catch (IOException ex) { ex.printStackTrace(); } catch (InterruptedException ex) { ex.printStackTrace(); } } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().executeExternalProgram(); }}
用户点评