簡體   English   中英

Java-具有自定義OutputStream的PrintStream上的異常行為

[英]Java - Strange behaviour on PrintStream with custom OutputStream

我正在嘗試編寫一個將System.out重定向到JTextArea的程序(它不必是JTextArea),但是當我調用System.out.println(“ Test!”)時,輸出到文本區域就像所以:

\n
st!
\n

我的OutputStream的代碼:

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);

誰能告訴我地球上正在發生什么?

基本上,您的代碼不是線程安全的。

您正在接受一個接受一個字節數組的同步調用,然后稍后再使用該字節數組,並假設它仍具有相同的內容。 如果在方法返回后, write()的調用者立即覆蓋字節數組中的數據,該怎么辦? 當您開始使用它時,您將沒有正確的數據。

我會在您的write調用中從字節數組中提取String ,然后在對write0的調用中使用該String

(我個人也使用Writer而不是OutputStream基本上,您要處理文本數據,而不是二進制數據。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM