在文本区域中显示OutputStream(System.out)

时间:2014-04-27 06:52:17

标签: java textarea outputstream

我使用Channel.setOutputStream(System.out),现在我想在textArea中显示结果。 我怎样才能做到这一点? 这是我的代码:

 public static void main(String[] args) throws JSchException, InterruptedException {

    JSch jSch = new JSch();
    Session session = jSch.getSession(user , host , 22);
    session.setPassword(password);
    session.setConfig("StrictHostKeyChecking" , "no");
    session.connect(10*1000);
    System.out.println("Connected");

    Channel channel = session.openChannel("shell");
    InputStream is = new ByteArrayInputStream(command.getBytes());
    channel.setInputStream(is);
    channel.setOutputStream(System.out);

    channel.connect(15*1000);

    Thread.sleep(3*1000);

    channel.disconnect();
    session.disconnect();


}

感谢。

1 个答案:

答案 0 :(得分:0)

package functions;

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

import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

/**
 *
 * @author Admin
 */
public class TextAreaOutputStream extends OutputStream {

    private final JTextArea textArea;
    private final StringBuilder sb = new StringBuilder();
    private final String title;

    /**
     *
     * @param textArea
     * @param title
     */
    public TextAreaOutputStream(final JTextArea textArea, String title) {
        this.textArea = textArea;
        this.title = title;
        sb.append("").append("");
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() {
    }

    @Override
    public void write(int b) throws IOException {

        /*if (b == '\r')
         return;*/
        if (b == '\n') {
            final String text = sb.toString() + "\n";
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    textArea.append(text);
                }
            });
            sb.setLength(0);
            StringBuilder append;
            append = sb.append("").append("");

            return;
        }

        sb.append((char) b);
    }

    /**
     *
     * @return
     */
    public StringBuilder getSb() {
        return sb;
    }
}