2013-04-20 44 views
0

我想寫一個程序,重定向System.out到JTextArea(它不一定是一個JTextArea),但是當我打電話System.out.println(「 !測試「)輸出到文本區是像這樣:Java - 與自定義OutputStream PrintStream奇怪的行爲

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

任何人都可以告訴我地球上發生了什麼?

+1

這代碼在這裏顯示編譯錯誤。爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 – 2013-04-20 08:15:51

+0

如何調用寫入函數?它有什麼論點? – Zyerah 2013-04-20 08:16:11

+0

「\ n」是逐字顯示的嗎? 'getDocument()'返回的類型是什麼,以及它是如何處理換行符的? – 2013-04-20 08:18:28

回答

1

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

您正在接受同步調用接受字節數組 - 然後您稍後使用該字節數組,並假定它仍將具有相同的內容。方法返回後,如果調用者write()立即覆蓋字節數組中的數據,該怎麼辦?到你使用它的時候,你將沒有正確的數據。

我會從中提取字節數組Stringwrite電話,然後使用String在調用write0

(我還親自使用Writer而非OutputStream - 從根本上要處理的文本數據,而不是二進制數據)

+0

工作完美 - 謝謝! – condorcraft110 2013-04-20 08:45:44