代碼:
import java.io.IOException;
public class TestRT {
/**
* 使用Runtime對象的exec方法,調用外部exe文件。
*/
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
try {
rt.exec("mspaint.exe"); //打開畫圖程序
rt.exec("C:\\Program Files (x86)\\Tencent\\QQ\\QQProtect\\Bin\\QQProtect.exe"); //"C:\\Program Files
//(x86)\\Tencent\\QQ\\QQProtect\\Bin\\QQProtect.exe"
} catch (IOException e) {
e.printStackTrace();
}
}
}
說明:
每個java運行程序都有一個Runtime運行實例,作用是使得應用程序與當前的運行環境對接。通過getRuntime()獲取實例。
引用程序不能創建該實例(環境嘛,只能獲取)
1. static Runtime getRuntime()
返回與當前 Java 應用程序相關的運行時對象。
2. Process exec(String command)
在單獨的進程中執行指定的字符串命令。
代碼2:
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import javax.swing.JOptionPane;
- public class TestRT {
- public final static int END_MARK = 0;
- /**
- * 使用Runtime對象的exec方法,運行cmd命令。
- */
- public static void main(String[] args) {
- Runtime rt = Runtime.getRuntime();
- try {
- Process pr = rt.exec("ping www.hao123.com "); //運行cmd命令
- BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
- String s = br.readLine();
- String temp = "" ;
- while(null != s ){
- if(!"".equals(s.trim())) temp = s;
- System.out.println(s);
- s = br.readLine();
- }
- br.close();
- //導致當前線程等待,如果必要,一直要等到由該 Process 對象表示的進程已經終止。
- pr.waitFor();
- //此 Process 對象表示的子進程的出口值。根據慣例,值 0 表示正常終止。
- if (END_MARK == pr.exitValue()) {
- JOptionPane.showMessageDialog(null, temp );
- }
- } catch (IOException e) {
- e.printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process..."); Process p = Runtime.getRuntime().exec("notepad.exe"); // cause this process to stop until process p is terminated p.waitFor();//導致main主線程堵塞,直到Process p中斷terminated,繼續主線程繼續運行下去 // when you manually close notepad.exe program will continue here (導致mian主線程堵塞,直到) System.out.println("Waiting over."); } catch (Exception ex) { ex.printStackTrace(); } } }result:
Creating Process...
(堵塞中。。。直到關閉note 輸出waiting over,此時如果調用Process.exitValue(),可以得到0(程序正常結束) 1(非正常中斷))
Waiting over.