0

This is a simple example where I'm trying to write and read Objects stored in ArrayList to/from file.

Writing file is working. Reading file is working only for first Object in my ArrayList. How should I make this into a loop?

I tried with something like:

`while(ois !=null) {
    Person result = (Person) ois.readObject();
    persons.add(result);
}

but it's not working.

Here is full test code:

public class Data {
static ArrayList<Person> persons = new ArrayList<Person>();

public static void savePersons() throws IOException{
     FileOutputStream fout = null;
     ObjectOutputStream oos = null;

     /** Make 5 'Person' object for examle */
     for(int i = 0; i<5; i++){
     Person personTest = new Person("name", "surname", "email", "1234567890");
     persons.add(personTest);
     }

     try{
         fout = new FileOutputStream("C:\\data.dat", true);
         oos = new ObjectOutputStream(fout);
         oos.writeObject(persons);
         System.out.println("Saving '" +persons.size()+ "' Object to Array");
         System.out.println("persons.size() = " +persons.size());
         System.out.println("savePersons() = OK");

     } catch (Exception ex) {
         System.out.println("Saving ERROR");

     } finally {
         if(oos  != null){
             oos.close();
         } 
     }
}

public static void loadPersons() throws IOException{
    FileInputStream fis = null;
    ObjectInputStream ois = null;

    /** Clean 'persons' array for TEST of load data*/
    persons.removeAll(persons);

    try {
        fis = new FileInputStream("C:\\data.dat");
        ois = new ObjectInputStream(fis);

        Person result = (Person) ois.readObject();
        persons.add(result);

        System.out.println("-------------------------");
        System.out.println("Loading '" +persons.size()+ "' Object from Array");
        System.out.println("persons.size() = " +persons.size());
        System.out.println("loadPersons() = OK");

    } catch (Exception e) {
        System.out.println("-------------------------");
        System.out.println("Loading ERROR");

    } finally {
        if(ois != null){
            ois .close();
        } 
    }
  }
}

Person class:

public class Person implements Serializable {
private String name;
private String surname;
private String mail;
private String telephone;
Person person;

public Person(String n, String s, String m, String t){
    name = n;
    surname = s;
    mail = m;
    telephone = t;
}

public String getName() {
    return name;
}

public String getSurname() {
    return surname;
}

public String getMail() {
    return mail;
}

public String getTelephone() {
    return telephone;
}}

Main class:

public class Test {

public static void main(String[] args) {
        Data.savePersons();
        Data.loadPersons();
}}
9
  • 1
    Show the Person class, please Commented Dec 9, 2016 at 20:17
  • 4
    You're writing the complete ArrayList to the file, so readObject will return an ArrayList and not a Person. Commented Dec 9, 2016 at 20:22
  • @cricket_007 i just added my 'person' class Commented Dec 9, 2016 at 20:23
  • Please also include a main method or separate test class that runs your program, not just an out of context code snippet Commented Dec 9, 2016 at 20:30
  • Try using persons = (ArrayList<Person>) ois.readObject(); instead of Person result = (Person) ois.readObject(); persons.add(result); Commented Dec 9, 2016 at 20:32

1 Answer 1

2

Here you go... please take note of the following:

YES, Chetan Jadhav CD's suggestion WORKS. B Use an IDE like Eclipse to help you debug your code and make your life easier. Be clear about what your error is (show stack trace, etc..) Note the modification to your catch clause that prints:

System.out.println("Saving ERROR: " + ex.getMessage()); 

Put all your code in one file before you ask for help to make everyone's life easier. Make each 'Person' at least someone unique by numbering them with your index Use .ser for a serializable file, rather than .dat

import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

public class Data {
    private static final String SER_FILE = "C:\\view\\data.ser";
    static List<Person> persons = new ArrayList<Person>();

    public static void main(String[] args) throws IOException {
        Data.savePersons();
        Data.loadPersons();
    }

    public static void savePersons() throws IOException {

        /** Make 5 'Person' object for example */
        for (int i = 0; i < 5; i++) {
            Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890-" +i);
            persons.add(personTest);
        }

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SER_FILE, true));) {

            oos.writeObject(persons);
            System.out.println("Saving '" + persons.size() + "' Object to Array");
            System.out.println("persons.size() = " + persons.size());
            System.out.println("savePersons() = OK");

        } catch (Exception ex) {
            System.out.println("Saving ERROR: " + ex.getMessage());
        }
    }

    public static void loadPersons() throws IOException {

        /** Clean 'persons' array for TEST of load data */
        persons.removeAll(persons);

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SER_FILE));){

            persons = (List<Person>) ois.readObject(); 
            //persons.add(result);

            System.out.println("-------------------------");
            System.out.println("Loading '" + persons.size() + "' Object from Array");
            System.out.println("persons.size() = " + persons.size());
            System.out.println("loadPersons() = OK");

            persons.stream().forEach(System.out::println);

        } catch (Exception e) {
            System.out.println("-------------------------");
            System.out.println("Loading ERROR: " + e.getMessage());

        }
    }
}

class Person implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String name;
    private String surname;
    private String mail;
    private String telephone;

    public Person(String n, String s, String m, String t) {
        name = n;
        surname = s;
        mail = m;
        telephone = t;
    }

    public String getName() {
        return name;
    }

    public String getSurname() {
        return surname;
    }

    public String getMail() {
        return mail;
    }

    public String getTelephone() {
        return telephone;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", surname=" + surname + ", mail=" + mail + ", telephone=" + telephone + "]";
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

"But you needed to use .ser instead of .dat first" - Technically, the file extension does not matter as long as you are saving and loading the same file; .ser is just a common convention.
Thank you Bradley D. I found one thing which make crash my every trying. It's missing variable: "private static final long serialVersionUID = 1L" in Person (Serializable class).
Exactly why you should use an IDE like Eclipse
@BradleyD Your code still doesn't work properly. Scenario: Save 5 Person to ArrayList -> Load 5 Person -> Close app -> Change number of people to save to 10 Person -> Save 10 Person -> And after this, app still read only 5 Person from file. What's wrong ?
I guess you didn't read my notes before the code. Saying the code doesn't work properly without giving any indication of what the error you're getting isn't how you ask for help on this site. Do the things I suggested above. Then paste your error message/stack trace
|

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.