在java中正确序列化对象

时间:2014-01-26 16:26:48

标签: java object serialization

谁能帮我发现错误?我试图通过序列化将文件people.txt(包括200行如'Christel; MacKay; 4“2'; 38')的某些信息(最小/最大/平均年龄)传递给另一个文件。 这是第一堂课,我处理这些人的一些信息:

import java.io.Serializable;

    @SuppressWarnings("serial")
    public class Person implements Serializable
    {
         private String firstname;
         private String lastname;
         private int age;

     public Person (String PersonFN, String PersonLN, int PersonA)
     {
         firstname = PersonFN;
         lastname = PersonLN;
         age = PersonA;
     }

     public String toString()
     {
          return "Name: "+firstname+" "+lastname+" Age: "+age;

     }

     public int getAge()
     {
         return age;
     }

    }

另一个,完成所有工作:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;



public class Collection
{
    int min;
    int max;
    int total;

    private static ArrayList<Person> people;

    public Collection()
    {
        people = new ArrayList<Person>();
        min = 100;
        max = 1;
        total = 0;
    }

    BufferedReader fr = null;
    BufferedWriter fw = null;

    public void readFromFile() throws IOException
    {
        fr = new BufferedReader (new FileReader("people.txt"));
        String line = null;
        StringTokenizer st;
         while (fr.ready())
        {
            line = fr.readLine();
            st = new StringTokenizer(line);           
            String name = st.nextToken(";");
            String surname = st.nextToken(";").toUpperCase();
            String height = st.nextToken(";");
            int age =  Integer.parseInt(st.nextToken(";").trim());
            Person p = new Person (name, surname, age);
            p.toString();
            people.add(p);

            //for the 2nd part
            if(age < min)
                min = age;
            if (age > max)
                max = age;
            total = total + age;

        }

    }

    public int minAge()
    {
        int minA = 100;
        for (int i = 0; i < people.size(); i++)
        {
            Person p = people.get(i);
            int age = p.getAge();
            if (age < minA)
            {
                minA = age;

            }
        }
        System.out.print(minA+"; ");
        return minA;
    }

    public int maxAge()
    {
        int maxA = 1;
        for (int i = 0; i < people.size(); i++)
        {
            Person p = people.get(i);
            int age = p.getAge();
            if (age > maxA)
            {
                maxA = age;

            }
        }
        System.out.print(maxA+"; ");
        return maxA;
    }

    public float avgAge()
    {
        int sum = 0;
        for (int i = 0; i < people.size(); i++)
        {
            Person p = people.get(i);
            int age = p.getAge();
            sum = sum + age;
        }
        float avgA = sum / people.size();
        System.out.print(avgA);
        return avgA;


    }

    public int fastMinAge()
    {
        //System.out.print("Minimum age: " + min);
        return min;

    }

    public int fastMaxAge()
    {
        return max;
    }

     public float fastAvgAge()
     { 
         return total / people.size();
     }


    public void writeToFile(String filename) throws IOException
    {

         StringBuffer val = new StringBuffer ("Minimum age: ");
         val.append(fastMinAge());
         val.append("\n Maximum age: ");
         val.append(fastMaxAge());
         val.append("\n Average age: ");
         val.append(fastAvgAge());

         BufferedWriter out = new BufferedWriter(new FileWriter(filename));
         String outText = val.toString();
         out.write(outText);
         out.close();
    }


    public static void main(String[] args) throws IOException, ClassNotFoundException
    {
        Collection c = new Collection();
        c.readFromFile();

        for(Person d: people)
        {
            System.out.println(d);

        }
      c.minAge();
      c.maxAge();
      c.avgAge();
      c.fastMinAge();
      c.fastMaxAge();
      c.fastAvgAge();
      c.writeToFile("RESULTS.txt");

      String filename = "people.txt";
      //FileOutputStream fos = new FileOutputStream(filename);
      ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename));
      os.writeObject(c);
      os.close();

      String filename1 = "results1.txt";
      FileInputStream fis = new FileInputStream(filename1);
      ObjectInputStream ois = new ObjectInputStream(fis);
      Collection p = (Collection) ois.readObject();
      ois.close();

    }

}

当我运行代码时,它会创建RESULTS.txt文件并在那里添加正确的信息。我确信代码的这一部分确实存在问题:

  String filename = "people.txt";
          //FileOutputStream fos = new FileOutputStream(filename);
          ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename));
          os.writeObject(c);
          os.close();

          String filename1 = "results1.txt";
          FileInputStream fis = new FileInputStream(filename1);
          ObjectInputStream ois = new ObjectInputStream(fis);
          Collection p = (Collection) ois.readObject();
          ois.close();

顺便说一句,我的people.txt文件变成了“¬ķ{sr java.io.NotSerializableException(Vxē†5 xrjava.io.ObjectStreamExceptiondĆäk¨9ūßxrjava.io.IOExceptionl€sde%š«xr java .lang.ExceptionŠż&gt ;;Äxrjava.lang.ThrowableÕĘ5'9wøĖLcauset Ljava / lang / Throwable; L detailMessaget Ljava / lang / String; [ stackTracet [Ljava / lang / StackTraceElement; L suppressExceptionst Ljava / util / List; xpq~t SD3lab1.Collectionur [Ljava.lang.StackTraceElement; F *&lt;&lt;ż“9 xp srjava.lang.StackTraceElementaÅ&amp;6Ż... I lineNumberL declaringClassq~L fileNameq~L methodNameq~xp˙˙˙˙tjava.io.ObjectOutputStreampt writeObject0sq~ ˙˙˙˙q~ptwriteObjectsq~    ©q~ t Collection.javat mainsr&amp; java.util.Collections $UnmodifiableListü%1μLLlistq~xr,java.util.Collections $ UnmodifiableCollectionB€Ė^÷L ct Ljava / util / Collection; xpsrjava.util.ArrayListxŅ™Ēa¯I sizexp w xq~x“,我在控制台上收到这些错误:

Exception in thread "main" java.io.NotSerializableException: SD3lab1.Collection
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at SD3lab1.Collection.main(Collection.java:169)

非常感谢任何帮助

1 个答案:

答案 0 :(得分:3)

您需要将Collection标记为Serializable

public class Collection implements Serializable {

此外,BufferedReaderBufferedWriter不可序列化,因此需要标记为transient

private transient BufferedReader fr;
private transient BufferedWriter fw;

同样使用诸如Collection之类的类名必然会引起混淆。考虑重命名该课程。