I can’t really think of a good reason why you’d want t send object data to std out (System.out), but I recently had a project requirement that a parent process read the output from a child process. The child process output was complex, so I wondered if I could send it as object data instead of text. I was told, “You can’t do that”, which is when I knew that I would find a way. Turns out, it was easier than expected. As you’ve probably guessed, sending text would be faster. I didn’t time it against sending text, so I don’t know by how much. If you time it, let me know your results.
Because System.out is a PrintWriter, it doesn’t behave like a regular output stream in that it is meant to handle Strings. However, there is a write(byte[] b) method that enables object data to be sent in the following way:
// set up output streams ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); // write some Serializable objects to ByteArrayOutputStream // using ObjectOutputStream wrapper Set<integer> keys = resources.keySet (); for(Integer key : keys) { oos.writeObject(new Integer(42)); oos.writeObject(new Integer(100)); } oos.close(); // send byte array to standard out System.out.write(bos.toByteArray()); |
You can then read the output of the process and create a byte array from that output. Once you have the byte array you can re-create your objects like so:
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(byteArr)); Integer i1 = (Integer)ois.readObject(); Integer i2 = (Integer)ois.readObject(); ois.close(); |