Saving your objects to file

Here is the class I made to handle saving of my Person objects in my GUI app. There is another way to save objects, using the serializable interface, but that is beyond the scope of this course.

 * To change this template, choose Tools | Templates
 * and open the template in the editor.
package basicapp;


 * @author robertsonj
public class FileHandler {

    final String FILE_PATH = "c:/app.txt";
    BufferedReader reader;
    PrintWriter writer;

    Person[] read() {
        // This is called by AppLogic.load() which runs when the AppLogic is
        // instantiated.

        // The array of Person objects that we create from the load file
        Person[] personArray = new Person[100];
        // This holds the current line from the load file
        String nextLine;
        // This is a two-element array that holds name/surname once it has
        // been split at the # sign
        String[] splitLine = new String[2];
        // This is just a counter of how many lines I've read in
        int count = 0;

        try {
            reader = new BufferedReader(new FileReader(FILE_PATH));
            // Get the first line
            nextLine = reader.readLine();
            // Loop until we've been through every line in the file
            while (nextLine != null) {
                // Split the current line at the # sign
                splitLine = nextLine.split("#");
                // Create a new person object
                Person p = new Person(splitLine[0], splitLine[1]);
                // Put it in the array
                personArray[count] = p;
                // Increment the counter
                count = count + 1;
                // Get the next line
                nextLine = reader.readLine();
        } catch (Exception e) {

        return java.util.Arrays.copyOfRange(personArray, 0, count);

    void write(Person[] p) {
        // This is called by, which runs when the MainForm
        // is close. It takes the Person array from the AppLogic and writes
        // it to file as a # delimited list.
        try {
            writer = new PrintWriter(new FileWriter(FILE_PATH));
            // Loop through each Person in the Person array
            for (int i = 0; i < p.length; i++) {
                // Write the name, then a # sign, then the surname
                writer.println(p[i].getFirstName() + "#" + p[i].getLastName());

        } catch (Exception e) {

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s