ObjectOutputStream does not write objects when taking BufferedOutputStream

I've done my research but it seems I can't find enough documentation on the subject.

When trying out some code on Object streams, I came to notice that putting a BufferedOutputStream inside an ObjectOutputStream causes the file to be ill-written. Just to makes things clearer here's the code I've used:

public class Objectstream implements Serializable{

private static final long serialVersionUID = 1L;
public int x;

public Objectstream(){}
public Objectstream(int x){
    this.x = x;
}

public static void main(String[] args) {

    try(
            //ObjectOutputStream objOutStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("/homes/f17oudbi/Bureau/o.txt")));//1
            ObjectOutputStream objOutStream = new ObjectOutputStream(new FileOutputStream("o.txt"));//2
            ObjectInputStream objInputStream = new ObjectInputStream(new FileInputStream("o.txt"));

            ){

        Objectstream obj = new Objectstream(7);

        objOutStream.writeObject(obj);
        objOutStream.flush();

        System.out.println(((Objectstream)objInputStream.readObject()).x);


    }catch(EOFException e){
        e.printStackTrace();
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

}

If I decomment the first line and comment the second, the written Objectstream just writes \AC\ED\00\00 in the file (and that's independant of how I change it); But if I keep the code as is, it writes something with the reference on the object and does the job well.

Does anyone have an explanation why is this the case?

Edit:

I get the following exception java.io.EOFException pointing to the line where the ObjectOutputStream method is created.

Jon Skeet
people
quotationmark

You're trying to create the ObjectInputStream on the same file that you're writing to - you never even get into the body of your try-with-resources block.

Here's what happens:

  • Create the FileOutputStream: file is empty
  • Wrap it in BufferedOutputStream: file stays empty
  • Wrap it in ObjectOutputStream: the OOS writes data to the BufferedOutputStream, but it's buffered
  • Create a FileInputStream
  • Create an ObjectInputStream - that tries to read from the input stream, finds it's empty, and throws an exception
  • The input stream is closed
  • The output stream is closed, which flushes the buffers and then you get the four bytes

Basically, I'd strongly advise you not to try to read from the same stream you're writing to - I doubt that this is the only problem it will cause.

people

See more on this question at Stackoverflow