我用类ObjectOutputStream向文件写读对象时,碰到一个问题:新建一个文
件,用输出流ObjectOutputStream向文件连续写几个对象,关闭输出流,然
后读取,这些对象都可以读出;这时在向该文件增加对象,新写的对象就读不出了,不知什么原因?请教了!(把下面的程序执行两遍就能看出了)还有我用记事本打开文件employee.txt里面有好多类似文件头的东西(personalfiancesystem.Employee镉 G靜彙 I ageD salaryL namet Ljava/lang/String;xpw),可能是这些文件头造成文件无法解析吧,但我不肯定,望高手!
package personalfiancesystem;
import java.io.*;class ObjectSerialTest
{
        public static void main(String[] args) throws Exception
        {         Employee[] e=new Employee[4];
                 e[0]=new Employee("zhangsan",25,3000.50);
                 e[1]=new Employee("lisi",24,3200.40);
                 e[2]=new Employee("wangwu",27,3800.55);
                 e[3]=new Employee("wangwu",27,3800.55);
                 FileOutputStream fos=new FileOutputStream("employee.txt",true);
                ObjectOutputStream oos=new ObjectOutputStream(fos);
                 for(int j=0;j<4;j++){
                oos.writeObject(e[j]);
             }
               oos.close();
               FileInputStream fis = new FileInputStream("employee.txt");
               ObjectInputStream ois = new ObjectInputStream(fis);
                  Employee e1;                  for (int i = 0; i < 4; i++) {
                      e1 = (Employee) ois.readObject();
                      System.out.println(e1.name + ":" + e1.age + ":" + e1.salary);
                  }
                  ois.close();
              }}class Employee implements Serializable
{
        String name;
        int age;
        double salary;        public Employee(String name,int age,double salary)
        {
                this.name=name;
                this.age=age;
                this.salary=salary;
        }
        private void writeObject(java.io.ObjectOutputStream oos) throws IOException
        {
                oos.writeInt(age);
                oos.writeUTF(name);
                System.out.println("Write Object");
        }
        private void readObject(java.io.ObjectInputStream ois) throws IOException
        {
                age=ois.readInt();
                name=ois.readUTF();
                System.out.println("Read Object");
        }}补充 程序第一次执行没问题,向文件中写入对象e[0],e[1],e[2];   e[0],e[1],e[2]
都能读出来,再执行一遍,又写入对象e[3]增加了一个对象,读文件时,应该读出e[0],e[1],e[2],e[3]啊,可它为什么只读出三个对象e[0],e[1],e[2]
而不是四个e[0],e[1],e[2],e[3]啊