简体   繁体   中英

Writing and Reading to/from a file Objects stored in ArrayList

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

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 + "]";
    }
}

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