0

我正在尝试编写一个将 System.out 重定向到 JTextArea 的程序(它不必是 JTextArea),但是当我调用 System.out.println("Test!") 时,文本区域的输出就像所以:

\n
st!
\n

我的输出流的代码:

package gui;

import java.awt.*;
import java.io.*;
import javax.swing.text.*;

public class LogOutputStream extends OutputStream
{
    public void write(final int b) throws IOException
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                write0(b);
            }
        });
    }

    public void write(final byte[] b, final int off, final int len)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                write0(b, off, len);
            }
        });
    }

    public void write(final byte[] b)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                write0(b);
            }
        });
    }

    private void write0(int b)
    {
        Document doc = FernflowerGUI.frame.textArea.getDocument();
        try
        {
            doc.insertString(doc.getLength(), String.valueOf((char)b), null);
        }
        catch(BadLocationException impossible)
        {

        }
    }

    private void write0(byte[] b, int off, int len)
    {
        Document doc = FernflowerGUI.frame.textArea.getDocument();
        try
        {
            doc.insertString(doc.getLength(), new String(b, off, len), null);
        }
        catch(BadLocationException impossible)
        {

        }
    }

    private void write0(byte[] b)
    {
        write0(b, 0, b.length);
    }
}

创建 PrintStream 的代码:

PrintStream ps = new PrintStream(new LogOutputStream(), true);

谁能告诉我地球上发生了什么?

4

1 回答 1

1

基本上,您的代码不是线程安全的。

您正在接受一个接受字节数组的同步调用 - 然后您稍后使用该字节数组,并假设它仍然具有相同的内容。如果调用者write()在方法返回后立即覆盖字节数组中的数据怎么办?当您开始使用它时,您将无法获得正确的数据。

我会String在您的调用中从字节数组中提取write,然后String在调用write0.

(我个人也会使用 aWriter而不是OutputStream- 基本上你想处理文本数据,而不是二进制数据。)

于 2013-04-20T08:39:48.543 回答