原文出處:http://blog.csdn.net/muiltmeta/archive/2002/05/08/16660.aspx
前一段時間看了《程序員》第
3
期
Java
專家門診中怎樣調用其它的程序,我把其解答代碼放到一個程序中,如下示:
import java.lang.*;
?
public class runProg{
public static void main(String[] args){
?????? try{
??????
? Runtime rt=Runtime.getRuntime();
??????
? rt.exec("NotePad");
?????? }catch(Exception e){}
}
}
?
?
?
?
?
?
?
?
?
?
?
?
在命令符下編譯運行,直接調用了記事本應用程序,沒有任何問題。
但在圖形用戶的應用程序中,就不能編譯,代碼示例如下:
? void jButton1_actionPerformed(ActionEvent e) {
??? //
下是解答代碼
try{
?????? Runtime rt=Runtime.getRuntime();
?????? rt.exec("NotePad");
??? }catch(Exception e){
}
//
上是解答代碼
? }
?
?
?
?
?
?
?
?
?
?
?
就上面的代碼而言,只是說明了調用其它程序的基本方法,但是這段代碼根本不能被編譯過去,在 Jbuilder 中的編譯錯誤如下:
"Frame2.java":
Error #: 469 : variable e is already defined in method
jButton1_actionPerformed(java.awt.event.ActionEvent) at line 50, column
18
?
?
?
?
看到這個編譯錯誤也許認為是按鈕的事件定義錯誤,實際上是 AWT 中 Component 的事件是線程安全級的,不允許直接使用另外進程或線程,因 Swing 中的組件是從 AWT 中繼承來的,所以也不允許直接使用。解決辦法只有使用一個新線程。代碼如下示:
? void jButton1_actionPerformed(ActionEvent e) {
??? //must be use a new thread.
??? Thread t = new Thread(new Runnable(){
??? public void run(){
?
???? try {
??????? Runtime rt = Runtime().getRuntime();
??????? rt.exec(“notepad”);
??????? } catch (IOException e) {
??????? System.err.println("IO error: " + e);
????? }
?
??}
??? });
??? t.start();
?
? }
但是這段代碼還是不能被編譯,錯誤提示如下:
"Frame1.java":
Error #: 300 : method Runtime() not found in anonymous class of method
jButton1_actionPerformed(java.awt.event.ActionEvent) at line 74, column
22
。
?
?
?
?
看到這段代碼,認為沒有發現 Runtime() ,或者沒有包含 Runtime 所在的包。但實際上是 java 每個 Application 都有一個自己的 Runtime ,所以不允許顯式聲明和使用另外一個。其實,許多文章也都是這么介紹的。在這里必須使用 Process 來啟用另外一個進程使用 Runtime 。代碼示例如下:
? void jButton1_actionPerformed(ActionEvent e) {
??? //must be use a new thread.
??? Thread t = new Thread(new Runnable(){
??? public void run(){
????? try {
??????? //String[] arrCommand = {"javaw", "-jar", "d:/Unicom/Salary/Salary.jar"};
????????????? // Process p = Runtime.getRuntime().exec(arrCommand);
??????? Process p = Runtime.getRuntime().exec("notepad");
??????? p.waitFor();
??????? System.out.println("return code: " + p.exitValue());
????? } catch (IOException e) {
??????? System.err.println("IO error: " + e);
????? } catch (InterruptedException e1) {
?????
??System.err.println("Exception: " + e1.getMessage());
????? }
??? }
??? });
??? t.start();
?
? }
運行后,點擊 jButton1 調用了 Windows 中的記事本應用程序。這里,新線程使用了 Runnable 接口,這是一種常用的技巧。另外,還必須要捕獲 IOException 和 InterruptedException 兩個異常。對于調用帶有參數的復雜程序,要使用字符串數組代替簡單的字符串,我在上面的代碼注釋了。