2013-04-20 43 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