为什么对象序列化方法中的readOject方法只能读取最新的那个writeObject呢,意思是假如我用writeObject存储多个对象到指定的路径下,当我调用readObject方法时候却仅仅只能读取最后的一个writeObject存储对象,前面都被覆盖了,这样很不方便啊,有没有什么解决方法呢(举例说是假如我用writeObject分别存储了Student stu1 、stu2、stu3,但是存储完毕后我调用readObject仅仅只能显示stu3的信息),后来我用list集合的形式,虽然能将这三个对象都显示出来,但是啊又觉得对象序列化是不是又有点多余呢。。。我等于又属于兜圈子了,下面给大家看看我的代码
package TestIO;
import java.io.Serializable;
class Student implements Serializable
{
private String name;
private int age;
private String pro;
private float score;
public Student(String name, int age, String pro, float score) {
super();
this.name = name;
this.age = age;
this.pro = pro;
this.score = score;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getPro() {
return pro;
}
public float getScore() {
return score;
}
}
package TestIO;
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.util.ArrayList;
import java.util.Scanner;
class RW
{
public ArrayList<Student> al=new ArrayList<Student>();
void Rw()
{
}
public void writeIO() throws FileNotFoundException, IOException
{
System.out.println("请依次输入学生的姓名、年龄、课程、分数:");
Scanner in=new Scanner(System.in);
String name=in.next();
int age=in.nextInt();
String pro=in.next();
float score=in.nextFloat();
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("C:\\Student.txt"));
Student stu=new Student(name,age,pro,score);
oos.writeObject(stu);
oos.close();
System.out.println("存储成功");
}
public void readIO() throws FileNotFoundException, IOException, ClassNotFoundException
{
int i=1;
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("C:\\Student.txt"));
Student stu=(Student)ois.readObject();
al.add(stu);
ois.close();
}
public void Out()
{
while(!al.isEmpty())
{
int i=0;
Student stu=al.get(0);
System.out.println("name="+stu.getName()+"\t"+"age="+stu.getAge()+"\t"+"pro="+stu.getPro()+"\t"+"score="+stu.getScore());
al.remove(i);
i++;
}
}
}
package TestIO;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Seriz
{
public static void main(String[]args) throws FileNotFoundException, IOException, ClassNotFoundException
{
RW rw=new RW();
for(int i=0;i<3;i++)
{
rw.writeIO();
rw.readIO();
}
rw.Out();
}
}
|