Java中截獲標(biāo)準(zhǔn)輸出到GUI控件
以前在使用Java開發(fā)項(xiàng)目時(shí),曾遇到這么一種情景:在一個(gè)Eclipse插件工程中,當(dāng)插件運(yùn)行后進(jìn)行多線程仿真執(zhí)行,這時(shí)需要捕獲并輸出Java的標(biāo)準(zhǔn)輸出流和錯(cuò)誤流。
View Code
View Code
1. 解決思路
Java中System類提供了可以重定向的方法setOut(PrintStream out)、setErr(PrintStream err)、setIn(InputStream in)。因此,使用setOut和setErr就夠了,這二個(gè)方法都要傳入一個(gè)PrintStream類型的參數(shù),只要在調(diào)用打印信息的前面調(diào)用這二個(gè)方法重設(shè)輸出流和錯(cuò)誤流就可以達(dá)到我們的目的。因此,通過繼承PrintStream類,并把要顯示信息的組件作為參數(shù)傳入到這個(gè)自定義的打印流類PrintStream中。
2. 代碼示例
View Code
1 /**
2 * @author ypf
3 * @version 1.0
4 * Created on 2009-11-4
5 * Description: the override PrintStream for catching Java standard
6 * console output to SWT dialog's Text control.
7 */
8 publicclass ConsolePrintStream extends PrintStream {
9 private Text text;
10
11 public ConsolePrintStream(OutputStream out, Text text) {
12 super(out);
13 this.text = text;
14 }
15
16 /**
17 * 重截write方法,所有的打印方法都要調(diào)用的方法
18 */
19 publicvoid write(byte[] buf, int off, int len) {
20 final String message =new String(buf, off, len);
21 if (text !=null&&!text.isDisposed()) {
22 /* SWT非界面線程訪問組件的方式 */
23 Display.getDefault().syncExec(new Thread() {
24 publicvoid run() {
25 /* 在這里把信息添加到組件中 */
26 text.append(message);
27 }
28 });
29 } else {
30 super.write(buf, off, len);
31 }
32 }
33 }
注意:確保GUI組件在調(diào)用打印信息添加前已經(jīng)被正確創(chuàng)建的,另外必須注冊不同GUI組件對線程的訪問形式,像上面的SWT就對界面的訪問有嚴(yán)格的規(guī)定。
3. 使用方法
在啟動GUI界面程序之后,按照如下方式調(diào)用代碼:
View Code
1 ConsolePrintStream cps=new ConsolePrintStream(System.out, text); // text為GUI組件
2
3 System.setOut(cps);
4
5 System.setErr(cps);
之后,Java標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤就被重定向到設(shè)置的GUI組件上了。

浙公網(wǎng)安備 33010602011771號