简体   繁体   中英

Correctly serializing objects in java

can anyone help me to spot the mistake? I am trying to pass certain information (min/max/avg ages) from file people.txt (which consists of 200 lines like 'Christel ; MacKay ; 4"2' ; 38'), to another file, by serializing. Here's the first class, where I process some info about these people:

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;
     }

    }

And another one, which does all the job:

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();

    }

}

When I run the code, it creates the RESULTS.txt file and adds the correct information there. I'm sure there's something wrong with this exact part of code:

  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();

By the way, my people.txt file changes into "¬ķ {sr java.io.NotSerializableException(Vx ē†5 xr java.io.ObjectStreamExceptiondĆäk¨9ūß xr ?java.io.IOExceptionl€sde%š« xr ?java.lang.ExceptionŠż>;Ä xr ?java.lang.ThrowableÕĘ5'9wøĖ L causet Ljava/lang/Throwable;L detailMessaget Ljava/lang/String;[ stackTracet [Ljava/lang/StackTraceElement;L suppressedExceptionst ?Ljava/util/List;xpq ~ t SD3lab1.Collectionur [Ljava.lang.StackTraceElement;F*<<ż"9 xp sr java.lang.StackTraceElementa Å&6Ż… I lineNumberL ?declaringClassq ~ L fileNameq ~ L methodNameq ~ xp˙˙˙˙t java.io.ObjectOutputStreampt writeObject0sq ~ ˙˙˙˙q ~ ?pt ?writeObjectsq ~ ©q ~ t ?Collection.javat mainsr &java.util.Collections$UnmodifiableListü?%1µģˇ? L listq ~ xr ,java.util.Collections$UnmodifiableCollectionB €Ė^÷ L ct Ljava/util/Collection;xpsr ?java.util.ArrayListxŅ™Ēa¯ I sizexp w xq ~ x", and I get these errors on the console:

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)

MANY THANKS FOR ANY HELP

You need to mark Collection as Serializable

public class Collection implements Serializable {

In addition BufferedReader and BufferedWriter are not serializable so need to be marked as transient

private transient BufferedReader fr;
private transient BufferedWriter fw;

Also using a class name such as Collection is bound to cause confusion. Consider renaming the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM