java里把一个类对象序列化后,存入文件,在读出时,只能读出第一个,再读的话就异常了,怎么解决
java里把一个类对象序列化后,存入文件,在读出时,只能读出第一个,再读的话就异常了,怎么解决
解决这个最好的办法就是把序列化和反序列化写一个共用方法。这样就可以反复使用了。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerializableTest {
//保存序列化对象方法
private static void save(Person person, String savePath){
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(savePath));
out.writeObject(person);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//反序列化对象方法
public static Person getPerson(String readPath){ //显示序列化后对象的方法
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(readPath));
return (Person)in.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
//这里可以创建N个Person对象
Person person1 = new Person();
person1.setName("SoulCrow1");
person1.setAge(23);
Person person2 = new Person();
person2.setName("SoulCorw2");
person2.setAge(25);
save(person1, "c:/person1.dat"); //将第一个Person对象序列化
save(person2, "c:/person2.dat"); //将第二个Person对象序列化
Person p1 = getPerson("c:/person1.dat");
System.out.println("person1-name:" + p1.getName());
System.out.println("person1-age:" + p1.getAge());
Person p2 = getPerson("c:/person2.dat");
System.out.println("person2-name:" + p2.getName());
System.out.println("person2-age:" + p2.getAge());
}
}
class Person implements Serializable{
private static final long serialVersionUID = -3626274979005298335L;
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
希望对你有帮助。