In the past, when I was using a Java Development Project, I encountered such a scenario: In an Eclipse plug-in project, when the plug-in runs, it is simulated and executed in multiple threads, in this case, the standard output stream and error stream of Java must be captured and output.
1. Solution
In Java, the system class provides the redirection Methods setout (printstream out), seterr (printstream ERR), and setin (inputstream in ). Therefore, it is enough to use setout and seterr. Both methods must pass in a printstream parameter, you only need to call these two methods before calling the print information to reset the output stream and error stream. Therefore, by inheriting the printstream class and passing the component for displaying information into the custom printstream class as a parameter.
2. Code Example 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 Public Class Consoleprintstream Extends Printstream {
9 Private Text text;
10
11 Public Consoleprintstream (outputstream out, text ){
12 Super (Out );
13 This . Text = Text;
14 }
15
16 /**
17 * Indicates the method used to re-intercept the write method. All printing methods must be called.
18 */
19 Public Void Write ( Byte [] Buf, Int Off, Int Len ){
20 Final String message = New String (BUF, off, Len );
21 If (Text ! = Null && ! Text. isdisposed ()){
22 /* How SWT non-interface threads Access Components */
23 Display. getdefault (). syncexec ( New Thread (){
24 Public Void Run (){
25 /* Add the information to the component */
26 Text. append (Message );
27 }
28 });
29 } Else {
30 Super . Write (BUF, off, Len );
31 }
32 }
33 }
Note: Make sure that the GUI component has been correctly created before the call printing information is added. In addition, you must register different GUI components to access the thread, as shown in the precedingSWTThere are strict rules for access to the interface.
3. Usage
Start the GUIProgramThen, call the Code as follows:
View code
1 Consoleprintstream CPS=NewLeleprintstream (system. Out, text );//Text is a GUI Component
2
3 System. setout (CPS );
4
5 System. seterr (CPS );
Then, java standard output and standard errors are redirected to the configured GUI component.