如何在Java中将控制台内容重定向到文本区域?

2022-09-03 06:01:32

我正在尝试在java的文本区域中获取控制台的内容。

例如,如果我们有此代码,

class FirstApp {
    public static void main (String[] args){
        System.out.println("Hello World");
    }
}

并且我想将“Hello World”输出到文本区域,我必须选择什么操作?


答案 1

我发现了这个简单的解决方案:

首先,您必须创建一个类来替换标准输出:

public class CustomOutputStream extends OutputStream {
    private JTextArea textArea;

    public CustomOutputStream(JTextArea textArea) {
        this.textArea = textArea;
    }

    @Override
    public void write(int b) throws IOException {
        // redirects data to the text area
        textArea.append(String.valueOf((char)b));
        // scrolls the text area to the end of data
        textArea.setCaretPosition(textArea.getDocument().getLength());
        // keeps the textArea up to date
        textArea.update(textArea.getGraphics());
    }
}

然后,按如下方式替换标准:

JTextArea textArea = new JTextArea(50, 10);
PrintStream printStream = new PrintStream(new CustomOutputStream(textArea));
System.setOut(printStream);
System.setErr(printStream);

问题是所有输出将仅显示在文本区域中。

带样本的来源:http://www.codejava.net/java-se/swing/redirect-standard-output-streams-to-jtextarea


答案 2

消息控制台为此显示了一个解决方案。


推荐