Serialization and append of Java objects and solutions for reading multiple objects in Java.
In the past few days, I used Object serialization knowledge to create a small chat project. I found that object serialization cannot directly append objects like normal files. Each write object will be overwritten. After more than two hours, we finally solved the problem. Java's default Object serialization is that each time an object is written, a bit of header aced 0005 (4 bytes) will be written. Then, each read will read the header and then read the content. The solution is to first determine whether the file exists. If it does not exist, create a file first. Then the first object is written, and the header is also written to aced 0005. When the append object is determined to exist, the 4-byte header aced 0005 is truncated and then the object is written to the file. This achieves Object serialization append. The Code is as follows:
String filename = m. getGetter () + m. getSender (); File file = new File ("D: \" + filename + ". txt "); if (file. exists () {isexist = true; FileOutputStream fo = new FileOutputStream (file, true); ObjectOutputStream oos = new ObjectOutputStream (fo); long pos = 0; if (isexist) {pos = fo. getChannel (). position ()-4; fo. getChannel (). truncate (pos);} oos. writeObject (m); // serialized} else {// file does not exist. createNewFile (); FileOutputStream f O = new FileOutputStream (file); ObjectOutputStream oos = new ObjectOutputStream (fo); oos. writeObject (m); // serialization} below is the serialization implementation. Be sure to close the stream outside the loop. If the stream is closed inside, the handle is invalid. String fileName = owner + friendNo; File file = new File ("D:" + File. separator + fileName + ". txt "); if (file. exists () {ObjectInputStream ois; try {FileInputStream fn = new FileInputStream (file); ois = new ObjectInputStream (fn); while (fn. available ()> 0) {// indicates that the file still contains Message p = (Message) ois. readObject (); // read the object System from the stream. out. println (p. getCon);} ois. close (); // close the catch (Exception e1) {// TODO Auto-generated catch block e1.printStackTrace ();}