0

I'm writing a func with ObjectOutputStream and ObjectInputStream to import and export contact information into a file.

I have a exception java.io.StreamCorruptedException: invalid stream header: EFBBBFAC in part ObjectInputStream and I don't know fix it.

How to fix it, Thank you.

LienHe lh = new LienHe(name, phone, img);
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                                 new FileOutputStream("src/Bai6/lienhe.txt", true));
        out.writeObject(lh);
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FrmThemLienHe.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FrmThemLienHe.class.getName()).log(Level.SEVERE, null, ex);
    }



lst = new ArrayList<>();
    try {// exception
        ObjectInputStream in = new ObjectInputStream(
                               new FileInputStream("src/Bai6/lienhe.txt")));
        while (in.available() > 0) {
            LienHe lh = (LienHe) in.readObject();
            lst.add(lh);
        }
    } catch (ClassNotFoundException | IOException ex) {
        System.out.println(ex.getMessage());
    }
  • 2
    Maybe unrelated, but `in.available()` doesn't do what you think. – Henry May 27 '17 at 11:35
  • At first I used while (true) but an error occurred and I search the internet and see people do it. – Dân Nguyễn May 27 '17 at 11:42
  • 1
    What is correct and what you may see people do aren't necessarily the same thing. See the Javadoc. `available()` is not a valid test for end of stream. – user207421 May 27 '17 at 11:46
  • 1
    I search the internet and I see people planking, lying on train tracks, and doing all sorts of other stupid / unsafe things. You should only pay attention to coding examples provided by *good* sources. – Stephen C May 27 '17 at 11:51

2 Answers2

0

You can't append to an ObjectOutputStream without taking special measures. You should serialize the collection, and replace the entire file when you do so.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

You didn't say so, but I assume that you are running the first chunk of code multiple times (appending to the same file) and then running the second one once ... to read all of the objects that you wrote.

In effect, you are concatenating multiple object streams, and trying to read it as a single stream.

That won't work. The problem is that each of the streams starts with a special header. When you try to read the concatenation as a single stream, the reader will see an unexpected header. That's what causes the exception you are seeing.

The solution is to restructure your code so that the writer writes all of the objects to the same ObjectOutputStream.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216