简体   繁体   中英

Java read from file two different type of objects

In my file I have saved my hashmap in the header which I can succesfully read, but when I try to read the following bytes, I get an error:

java.io.StreamCorruptedException: invalid type code: C9
    at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(Unknown Source)

Here's my code:

    FileInputStream fis = new FileInputStream(filename);
    ObjectInputStream ois = new ObjectInputStream(fis);

    try {
        map = (HashMap<Integer, String>) ois.readObject();

        byte b = ois.readByte();

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

How I write:

        FileOutputStream os = new FileOutputStream(fileOutPath);
        ObjectOutputStream oos = new ObjectOutputStream(os);

        oos.writeObject(codePathMap);

        BitSet buffer = new BitSet();

        for (int i = 0; i < file.length; i++) {
            for (int y = 0; y < codePathMap.get(i).length(); i++) {
                if (codePathMap.get(b).charAt(i) == '1') {
                    buffer.set(bitIndex);
                }
            }
        }
        os.write(buffer.toByteArray());

There's a mismatch between writes and reads algorithms. Short story, you're using FileOutputStream in order to write your byte[] , but ObjectInputStream in order to read it. Those classes uses different ways of how they treat the stored data.

Hence, you SHOULD always use ObjectOutputStream/ObjectInputStream .

So, just to fix your error, instead of using FileOutputStream :

os.write(buffer.toByteArray());

you might use ObjectOutputStream (oos) in order to write the byte[] as:

oos.write(buffer.toByteArray());

Side note: invalid type code: C9 , C9 is actual value of the written byte[] , so C9 is 201 , which ObjectInputStream interprets as Java type (that's how ObjectOutputStream serializes the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM