2

I have saved an object to an array list and saved the file as .dat, but when I want to read the object it is just showing null and not the values.

The Class

public class Person implements Serializable {
  public static String Name;
  public static String Contact;

  public Person(String Name, String Contact) {
    this.Name = Name;
    this.Contact = Contact;
  }

  public String getName() {
    return Name;
  }

  public String getContact() {
    return Contact;
  }
}

The code

FileInputStream fis;
try {
  fis = new FileInputStream("Person.dat");
  ObjectInputStream ois = new ObjectInputStream(fis);
  ArrayList<Person> per = (ArrayList<Person>) ois.readObject();
  ois.close();

  per.get(0);
  Person pe = per.get(0);
  System.out.println(pe.getName());
} catch (FileNotFoundException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
} catch (IOException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
} catch (ClassNotFoundException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
}

2 Answers 2

5

You defined static members Name and Contact which are not serialized. Remove the static modifier to make this work.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, naming conventions should be followed (name and contact).
0

Only non-transient and non-static fields will be serialized.

Refer to oracle documentation page and jusfortechies article.

Change

public static String Name;
public static String Contact;

to

public String Name;
public String Contact;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.