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

狂风中的少年 提交于 2019-12-04 17:15:21
VonC

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)

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:

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