我知道Java I / O使用装饰器模式。但是我觉得我理解它的错。
请说明两个代码段之间的区别:
PipedInputStream pipedInputStream = new PipedInputStream(); PipedOutputStream pipedOutputStream = new PipedOutputStream(); pipedOutputStream.connect(pipedInputStream); ObjectOutputStream objectOutputStream = new ObjectOutputStream(pipedOutputStream); objectOutputStream.writeObject("this is my string"); ObjectInputStream objectInputStream = new ObjectInputStream(pipedInputStream); System.out.println(objectInputStream.readObject());
该应用程序符合我的期望,并且在控制台中看到结果。
我尝试两次包装ObjectInputStream和ObjectOutputStream:
PipedInputStream pipedInputStream = new PipedInputStream(); PipedOutputStream pipedOutputStream = new PipedOutputStream(); pipedOutputStream.connect(pipedInputStream); ObjectOutputStream objectOutputStream = new ObjectOutputStream(pipedOutputStream); ObjectOutputStream objectOutputStreamWrapper = new ObjectOutputStream(objectOutputStream); //double wrapping objectOutputStreamWrapper.writeObject("this is my string"); ObjectInputStream objectInputStream = new ObjectInputStream(pipedInputStream); ObjectInputStream objectInputStreamWrapper = new ObjectInputStream(objectInputStream); System.out.println(objectInputStreamWrapper.readObject());
这段代码只是挂断了。我不明白为什么。请澄清。
聚苯乙烯
这仅仅是理论问题。
真正的挂断行为是因为我使用管道而发生的(根据EJP回答)。
例如,此代码按预期工作。
OutputStream outputStream = new FileOutputStream("2.txt"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); ObjectOutputStream objectOutputStreamWrapper = new ObjectOutputStream(objectOutputStream); //double wrapping objectOutputStreamWrapper.writeObject("this is my string"); objectOutputStream.close(); ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("2.txt")); ObjectInputStream objectInputStreamWrapper = new ObjectInputStream(objectInputStream); System.out.println(objectInputStreamWrapper.readObject()); objectInputStream.close();
看起来如果我用10个装饰器包装输入,我应该用10个装饰器以相同顺序包装输出。是真的吗
我注意到仅冲洗的问题:
PipedInputStream pipedInputStream = new PipedInputStream(); PipedOutputStream pipedOutputStream = new PipedOutputStream(); pipedOutputStream.connect(pipedInputStream); ObjectOutputStream objectOutputStream = new ObjectOutputStream(pipedOutputStream); ObjectOutputStream objectOutputStreamWrapper = new ObjectOutputStream(objectOutputStream); //double wrapping objectOutputStreamWrapper.writeObject("this is my string"); objectOutputStreamWrapper.flush(); ObjectInputStream objectInputStream = new ObjectInputStream(pipedInputStream); ObjectInputStream objectInputStreamWrapper = new ObjectInputStream(objectInputStream); System.out.println(objectInputStreamWrapper.readObject());
您正在滥用管道流。它们打算由进行写操作的生产者线程和进行读操作的使用者线程使用。请参阅Javadoc。
管道传输的流共享一个缓冲区,如果读取线程不读取该缓冲区,则该缓冲区可以填满,这会使您的写入线程停滞。
将流包装两次与它没有任何关系,尽管在这种情况下,这肯定是毫无意义且有问题的。