Can I use a BufferedOutputStream with an ObjectOutputStream to serialize an object?

Tim Rohaly

Yes. In fact, it is recommended that you buffer all your input and output unless you have a good reason not to.

Here's an example of how to do this:

    String myobject = new String("myobject");
    FileOutputStream file = new FileOutputStream("myobject.ser");
    BufferedOutputStream bout = new BufferedOutputStream(file);
    ObjectOutputStream out = new ObjectOutputStream(bout);

Java allows you to chain I/O streams together. Using a BufferedOutputStream makes output much more efficient because the I/O overhead is then expended on large chunks of data, rather than on individual bytes.

Likewise, many times it makes sense to compress your output, say if you are writing many large objects to a file or a socket. You can do this using a ZipOutputStream or a GZIPOutputStream in place of (or in addition to!) the BufferedOutputStream in the above example.