多引号导致 PipedOutputStream/OutputStreamWriter 失败 [英] Multiple quotes cause PipedOutputStream/OutputStreamWriter to fail

查看:28
本文介绍了多引号导致 PipedOutputStream/OutputStreamWriter 失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将 OutputStream 复制到 InputStream 时,我偶然发现了 PipedOutputStream 的一个非常奇怪的行为.另请参阅如何以编程方式编写 nt:file

I stumbled over a very strange behavior with the PipedOutputStream when I was trying to copy an OutputStream to an InputStream. See also How to write an nt:file programmatically

这是一个小的单元测试方法:

Here is a small unit test method:

@Test
public void pipeTest() {
    PipedInputStream pin = null;
    try {
        pin = new PipedInputStream();
        PipedOutputStream pout = new PipedOutputStream(pin);
        OutputStreamWriter writer = new OutputStreamWriter(pout);
        for (int i = 0; i < 100; i++) {
            writer.write("\"Test\";" + i + "\n");
            // writer.write("\"Test\";" + "\"" + i + "\"\n");
        }

        writer.close();
        pout.close();

        System.out.print(IOUtils.toString(pin));
    } catch (IOException e) {
        System.out.print(e);
    } finally {
        IOUtils.closeQuietly(pin);
    }

}

这很有效并且打印出 100 行.如果您取消注释第二个 write 语句并注释掉第一个,writer.close() 会卡住并且永远不会完成.第二组引号 \" 似乎有问题.有没有人知道为什么会这样以及如何规避它?

This works well and prints out 100 rows. If you uncomment the second write statement and comment out the first, writer.close() gets stuck and never finishes. It seems to have problem with the second set of quotes \". Has anyone and idea why this is the case and how to circumvent it?

推荐答案

这与引号无关 - 而与您写入的数据量有关.为了证明这一点,您可以完全摆脱编写器和循环,只需使用:

This has nothing to do with the quotes - and everything to do with how much data you're writing. To demonstrate this, you can get rid of the writer and the loop entirely, and just use:

pout.write(new byte[1024]);

或者保留您现有的代码,但要注意这是否有效(因为它写入了 1000 个字节):

Or keep your existing code, but see that this works (because it writes 1000 bytes):

writer.write("0123456789");

但这不会(因为它尝试写入 1100 个字节):

but this doesn't (because it tries to write 1100 bytes):

writer.write("0123456789X");

那行得通——但如果你把它改成 1025,它将永远挂起……因为内部缓冲区默认为 1024 字节长,并且没有任何东西消耗流.(在完成写入之前,您不会从 pin 读取.)由于没有消耗前 1024 个字节中的任何一个,因此无处放置第 1025 个字节,因此 write 阻塞直到有 空间.

That works - but if you change it to 1025, it'll hang forever... because the internal buffer is 1024 bytes long by default, and nothing's consuming the stream. (You're not reading from pin until you've finished writing.) As nothing is consuming any of the first 1024 bytes, there's nowhere to put the 1025th byte, so write blocks until there is space.

你可以:

  • 在构建 PipedInputStream 时更改管道大小,这样它就有了更大的缓冲区
  • 在写作时从管道中读取 - 例如在一个单独的线程中.
  • Change the pipe size when you construct the PipedInputStream, so it's got a bigger buffer
  • Read from the pipe while you're writing - e.g. in a separate thread.

这篇关于多引号导致 PipedOutputStream/OutputStreamWriter 失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆