(Eclipse RCP) How to redirect the output to Console View?

懵懂的女人 提交于 2019-12-06 11:29:27

问题


I have two viewers, one has a Text for user's input and the other viewer is the Eclipse's built_in Console View. And I will run an java program according user's input, and want to display the log information in the ConsoleView. Does anybody know How can I redirect the output to Console View ?

Thanks


回答1:


SO questions How to write a hyperlink to an eclipse console from a plugin and writing to the eclipse console give example of redirection to the Console.

The blog post Displaying the console in your RCP application

The ideas remain to create an OuputStream and open a New Console, or associating the MessageStream of a console to stdout adn stderr (like my previous answer)




回答2:


Redirect output on RCP console:

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.annotation.PostConstruct;

import org.eclipse.e4.ui.di.Focus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;

public class ConsoleView {
    private Text text;

    @PostConstruct
    public void createPartControl(Composite parent) {
        text = new Text(parent,
                SWT.READ_ONLY | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);

        OutputStream out = new OutputStream() {
            StringBuffer buffer = new StringBuffer();

            @Override
            public void write(final int b) throws IOException {
                if (text.isDisposed())
                    return;
                buffer.append((char) b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                super.write(b, off, len);
                flush();
            }

            @Override
            public void flush() throws IOException {
                final String newText = buffer.toString();
                Display.getDefault().asyncExec(new Runnable() {
                    public void run() {
                        text.append(newText);
                    }
                });
                buffer = new StringBuffer();
            }
        };

        System.setOut(new PrintStream(out));
        final PrintStream oldOut = System.out;

        text.addDisposeListener(new DisposeListener() {
            public void widgetDisposed(DisposeEvent e) {
                System.setOut(oldOut);
            }
        });
    }

    @Focus
    public void setFocus() {
        text.setFocus();
    }
}

The screenshot:



来源:https://stackoverflow.com/questions/2127718/eclipse-rcp-how-to-redirect-the-output-to-console-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!