Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piped<I/O>Stream. Can I pass complex objects?

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?

like image 726
gstackoverflow Avatar asked Sep 12 '26 15:09

gstackoverflow


1 Answers

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

like image 133
m1o2 Avatar answered Sep 14 '26 05:09

m1o2