Home  >  Q&A  >  body text

About serialization and deserialization in Java

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中文网2702 days ago922

reply all(1)I'll reply

  • 漂亮男人

    漂亮男人2017-05-27 17:43:47

    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

    reply
    0
  • Cancelreply