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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With