Write and read an ArrayList object to a file in Java

3
52706

Today, we will get to know how to write an ArrayList object to a file and then load the object back to the Java program form that file. This would help us to store the data to test other features that we added to the program without re-putting the common data.

First, we’ll take a look at the code below

1. Since we will need to use a lot of classes inside java.io, we import everything inside that specific library.

2. Create a class Person with 3 attributes, a constructor function and overriding toString method to print the detail of an object we will initialize later. As this the objects of this class will be used to write to file and then load back, we need to implement the Serializable interface to indicate Java that this class can be serialized or deserialized.

3. inside this main methods we will create 3 objects of the class Person. Then, we create an ArrayList name people and add those 3 Person objects.

Now, we are ready to write this Arraylist into a file.

Write an object into a file.

We add this code to the main method.

//write to file
try{
    FileOutputStream writeData = new FileOutputStream("peopledata.ser");
    ObjectOutputStream writeStream = new ObjectOutputStream(writeData);

    writeStream.writeObject(people);
    writeStream.flush();
    writeStream.close();

}catch (IOException e) {
    e.printStackTrace();
}

Because writing and reading data can cause Error we need to use a try catch block to handle the Exception that can occur.

FileOutputStream writeData = new FileOutputStream(“peopledata.ser”): Creates a file output stream to write to the file that we provide inside the parentheses. You can provide the path to the file if you want, in this case, I just give the file name, so that the file will be stored in the same folder with the .java file

ObjectOutputStream writeStream = new ObjectOutputStream(writeData):  ObjectOutputStream will handle the object to be written into the file that FileOutputStream created.

FileOutputStream and ObjectOutputStream should come together in order to write an object to a file.

writeStream.writeObject(people): tell the program to write this peple object which is an ArrayList that we’ve just created above into the file peopledata.ser
writeStream.flush(): using the flush method here is not really necessary but it’s a good practice to have flush() since it will flush all the data in the stream, make sure data is written into the file.
writeStream.close(); we close the stream after the writing is done. This also releases the system resources.

Open the file peopledata.ser and you will see that there is something written. Don’t be afraid that you can’t read it, Java can.

��srjava.util.ArrayListx����a�IsizexpwsrPerson-ĩ��9/I birthYearL 
firtNametLjava/lang/String;L lastNameq~xp�tJonytDeepsq
~�tAndrewtJustinsq~�tValaktSusanx

Reading the data from a file

Writing is done, now we can load the data from the file to be used in our program.

Append the code below to the main method

try{
    FileInputStream readData = new FileInputStream("peopledata.ser");
    ObjectInputStream readStream = new ObjectInputStream(readData);

    ArrayList<Person> people2 = (ArrayList<Person>) readStream.readObject();
    readStream.close();
    System.out.println(people2.toString());
}catch (Exception e) {
    e.printStackTrace();
}

Still, we use try-catch to ensure that all the exceptions will be caught.

FileInputStream readData = new FileInputStream(“peopledata.ser”) & ObjectInputStream readStream = new ObjectInputStream(readData): note that this time we use Input instead of Ouput since we want to read from the file into the program.

ArrayList<Person> people2 = (ArrayList<Person>) readStream.readObject(): We create a new ArrayList people2 just to make sure this is a new object that is distinct from the existing people object. We assign the value that we reed form the file “peopledata.ser” and make sure we cast the value into an ArrayList of Person.

readStream.close(): close the reading stream.

System.out.println(people2.toString()): print the new ArrayList to the console to see if all the data is loaded correctly.

[Person{firtName='Jony', lastName='Deep', birthYear=1980}
, Person{firtName='Andrew', lastName='Justin', birthYear=1990}
, Person{firtName='Valak', lastName='Susan', birthYear=1995}
]

Yes, it’s correct.

import java.io.*;
import java.util.ArrayList;

public class Person implements Serializable {
    private String firstName;
    private String lastName;
    private int birthYear;

    public Person(String firtName, String lastName, int birthYear) {
        this.firstName = firtName;
        this.lastName = lastName;
        this.birthYear = birthYear;
    }

    @Override
    public String toString() {
        return "Person{" +
                "firtName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", birthYear=" + birthYear +
                "}\n";
    }

    public static void main(String[] args) {
        Person p1 = new Person("Jony", "Deep", 1980);
        Person p2 = new Person("Andrew", "Justin", 1990);
        Person p3 = new Person("Valak", "Susan", 1995);

        ArrayList<Person> people = new ArrayList<>();

        people.add(p1);
        people.add(p2);
        people.add(p3);

        //write to file
        try{
            FileOutputStream writeData = new FileOutputStream("peopledata.ser");
            ObjectOutputStream writeStream = new ObjectOutputStream(writeData);

            writeStream.writeObject(people);
            writeStream.flush();
            writeStream.close();

        }catch (IOException e) {
            e.printStackTrace();
        }

        try{
            FileInputStream readData = new FileInputStream("peopledata.ser");
            ObjectInputStream readStream = new ObjectInputStream(readData);

            ArrayList people2 = (ArrayList<Person>) readStream.readObject();
            readStream.close();

            System.out.println(people2.toString());
        }catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

 

3 COMMENTS

  1. I added , true to the fileoutput stream so that it appends the data and it doesnt overwrite it but when it tries to read the file again it doesnt read the extra person i have added even though I can see that the extra person had been added to the file. please help.

LEAVE A REPLY

Please enter your comment!
Please enter your name here