gpt4 book ai didi

Java - 使用自定义 OutputStream 的 PrintStream 上的奇怪行为

转载 作者:行者123 更新时间:2023-12-01 14:39:33 24 4
gpt4 key购买 nike

我正在尝试编写一个将 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);

谁能告诉我到底发生了什么?

最佳答案

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

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

我会在 write 调用中从字节数组中提取 String,然后在对 的调用中使用该 String写0

(我个人也会使用 Writer 而不是 OutputStream - 从根本上来说,您想要处理文本数据,而不是二进制数据。)

关于Java - 使用自定义 OutputStream 的 PrintStream 上的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16118191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com