About serialization and deserialization in Java
PHP中文网
PHP中文网 2017-05-27 17:41:47
0
1
983

1. The following code serializes file 2.log and saves it to 2.txt

    FileInputStream fin = new FileInputStream("D:\2.log");

    FileOutputStream out1 = new FileOutputStream(new File("D:\2.txt"));

    // ObjectOutputStream oop1 = new ObjectOutputStream(out1);

    byte[] datas = new byte[1024];

    int j = 0;

    while ((j = fin.read(datas)) > 0) {

        out1.write(datas);

        fin.read(datas);

    }

    fin.close();
    out1.close();

Deserialization:
Use ObjectInputStream()
FileInputStream fis = new FileInputStream("D:/2.txt");
ObjectInputStream oin = new ObjectInputStream(fis);
oin. readObject();
Error: Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 3139322E
How to deal with it?
If the file is large, how to add cache when reading? I hope Daniel can enlighten me, xiexie

PHP中文网
PHP中文网

认证0级讲师

reply all(1)
漂亮男人

Your problem is because the content read by ObjectInputStream must be generated by writing by ObjectOutputStream. The content of the file must comply with the specification requirements of Java serialization. The byte array you create yourself cannot be used.


protobuf is a flexible, efficient, and automatic method for serializing structured data, just like XML, but it is smaller, faster, and simpler. You can define your own data structure and then use the code generated by the code generator to read and write this data structure. You can even update data structures without redeploying the program.

Whether it is size or serialization and deserialization efficiency, it is basically at the forefront. It is several times better than the serialization that comes with JAVA. The larger the data, the more obvious the advantage. The disadvantage is that it is a little troublesome to operate

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template