jdk 1.8 IEDA
设置可以追加写入后,向目标文件序列化多个同一对象,再序列化出来时,因为反序列化时头部信息只读取一次,报出异常。
请问该怎么解决?或者代码写的有问题?
import java.io.*;
/**
* 完成多个对象的序列化和反序列化
*/
public class SerializationDeserialization {
public static void main(String[] args) {
Staff staff1 = new Staff("银灰", "近卫", 880, 400);
Staff staff2 = new Staff("伊芙利特", "术师", 748, 120);
Staff staff3 = new Staff("能天使", "狙击", 571, 140);
seralization(staff1);
seralization(staff2);
seralization(staff3);
File file = new File("arknights.txt");
try {
deseralization(file);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 序列化
* @param staff
*/
public static void seralization(Staff staff) {
//设置可以追加写入
try (ObjectOutputStream oosOut = new ObjectOutputStream(new FileOutputStream("arknights.txt", true))) {
oosOut.writeObject(staff);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 反序列化
* @param file
* @throws IOException
* @throws ClassNotFoundException
*/
public static void deseralization(File file) throws IOException, ClassNotFoundException {
ObjectInputStream oosIn = new ObjectInputStream(new FileInputStream(file));
Object obj;
while ((obj=oosIn.readObject())!=null) {
Staff staff=(Staff)obj; // Staff{name='银灰',position='近卫',atk='880',def='400'}
// java.io.StreamCorruptedException: invalid type code: AC
System.out.println(staff);
}
}
}