3

I investigate java I/O. Now I am reading about pipes.

I wrote simplest code example:

PipedInputStream pipedInputStream = new PipedInputStream();
PipedOutputStream pipedOutputStream = new PipedOutputStream();

pipedOutputStream.connect(pipedInputStream);

pipedOutputStream.write(new byte[]{1});
System.out.println(pipedInputStream.read());

I have following question. As I understand - it is very strange to pass bytes in real life.

Is it really to extend this example for pass entire String for example?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

1 Answers1

6

Yes. Decoreate it with ObjectInputStream and ObjectOutputStream.

PipedOutputStream pipedOutputStream = new PipedOutputStream();
PipedInputStream pipedInputStream = new PipedInputStream();

pipedInputStream.connect(pipedOutputStream);

ObjectOutputStream objectOutputStream = new ObjectOutputStream(pipedOutputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(pipedInputStream);

objectOutputStream.writeObject("Hello world!");
String message = (String)objectInputStream.readObject();

System.out.println(message);

More info on the decoration pattern and specifically for the Java I/O stream decoration, you can find in this StackOverFlow Post

BTW, make sure to Initiate the ObjectOutputStream before the ObjectInputStream and also to connect the pipes using the connect method before the creation of the Object input/output streams.
Here is why: http://frequal.com/java/OpenObjectOutputStreamFirst.html

Community
  • 1
  • 1
m1o2
  • 1,549
  • 2
  • 17
  • 27
  • @gstackoverflow I edited my code and added an example. – m1o2 Jun 29 '14 at 15:52
  • strange that if I make connect after wrapping - I get "Pipe not connected" – gstackoverflow Jun 29 '14 at 16:52
  • @gstackoverflow the ObjectInputStream will start some sort of a Handshake, and will wait for bytes to arrive from the ObjectOutputStream open(). So this is the issue. If the Piped are not connected, then the handshake and the initialization of the ObjectInputStream will fail. Try this link http://frequal.com/java/OpenObjectOutputStreamFirst.html – m1o2 Jun 29 '14 at 17:45
  • @m1o2 I wouldn't describe it as a 'handshake'. It just reads the stream header written by the `ObjectOutputStream` at the other end. – user207421 Jun 29 '14 at 23:47
  • 1
    Wow this worked unlike all my other attempts at trying to do the same (with other code samples too). Thank you. – Sridhar Sarnobat Sep 18 '19 at 18:14