JAVA的Runtime.getRuntime().exec(String cdm),可用來執行CDM(CONSOLE)指令,它會回傳Process物件,用getInputStream(),就可取得資廖流,這樣就可取得執行過程,在來我想把執行過程要一一顯示在文字示窗裡,要怎作呢?用jTextArea.append(),可以累加顯示,因此我用reaLline()一行一行的讀取緩衝區資料,在用jTextArea.append()累加顯示,照理應該可行,其實是不行的,後來終於知道,應該要啟動執行續,把jTextArea.append()累加顯示放到執行續去執行,,否則是無法同時進行,就不能看到CDM執行過程了,下面是一個專門處理CDM指令,並程呼叫layoutmain.appendtext(ls_str+"\n");把過程忠實呈現在文字區,比較有趣的是,我使用了建構元,
當產生runexec物件時,可初始物件(帶CDM指令),譬如
runexec re1=new runexec("cat /home/yplin/.cshrc");
這樣我這個re1物件就被初始化有一 private String cdm ;
後面有runexec class完整程示,和layoutmain與runexec如何互動的程示,也有2張我抓下來的圖,因為我想自己作一個工做上我須要的示窗界面,讓我更得心應手.
/*
* runexec.java
*
* Created on 2005年6月21日, 下午 10:18
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/
package layouttools;
import java.io.*;
import java.awt.*;
/**
*
* @author yplin
*/
public class runexec {
/** Creates a new instance of runexec */
private String cdm;
public runexec(String name){
cdm=name;
}
public void showrun() {
layoutmain.setlabel("正在執行 : "+cdm , Color.red);
//實做執行續,讓文字區能同時顯示執行過
new Thread (
new Runnable() {
public void run() {
try{
//把正在執行的迅息放到LABEL
String ls_str="";
Process ls_proc = Runtime.getRuntime().exec(cdm);
// get its output (your input) stream
BufferedInputStream buffer = new BufferedInputStream(ls_proc.getInputStream());
DataInputStream ls_in = new DataInputStream(buffer);
try {
while ((ls_str = ls_in.readLine()) != null ) {
//呼叫layoutmain.appendtext(),附
layoutmain.appendtext(ls_str+"\n");
}
//顯示執行完成
layoutmain.setlabel(cdm+"執行完成", Color.red);
} catch (java.io.IOException e) {}
ls_in.close();
} catch (IOException e1){}
}
}
).start();
}
}
/*
* layoutmain.java
*
* Created on 2005年6月19日, 下午 1:49
*/
package layouttools;
/**
*
* @author yplin
*/
import javax.swing.*;
import java.io.*;
import java.awt.*;
public class layoutmain extends javax.swing.JFrame {
........................................
.......................................
runexec re = new runexec("calibre -lvs /home/yplin/Amazion/lvs/lvs.com");
.......................................
.......................................
public static void appendtext(String name){
//附
jTextArea1.append(name);
}
public static void setlabel(String name,Color bg){
jLabel1.setBackground(bg);
jLabel1.setText(name);
jLabel1.setFont(new Font("Arial",Font.ITALIC,18));
jLabel1.setForeground(bg);
}
}
開始執行畫面
執行完成畫面