Ad

Saving All Contents Of Array Through A Class Into A File.txt And Then Loading / Saving / Reading From That Same File?

- 1 answer

I'm trying to save user input in a file I've referenced known as "contacts.txt". I have to collect user input and store them in a phonebook format and then allow the user to call information that they have saved in this file. I'm having trouble writing input to the "contacts.txt" file. The two functions this is referencing can be seen below are doSave() and doAddEntry().

I've been working at this for hours and have hit a brick wall, as well as have ran millions of debugs (probably incorrectly) to see where this is all going wrong...

Could anyone offer any insight that may be able to set me on the right track?

< Solved >

Ad

Answer

You should Make Entry a Serializable class and use Serialization to save the array of Entryobjects in a file and deserialization to get the array of objects back from the stream of bytes saved on file. For Example, consider the code given below . Here Person is a class which implements java.io.Serializablemarker interface. Within main body of SerializeArray an array of Person is created and it is saved in a file named Persons.ser (You can use any name here for the file) using saveArray. This array is then read back from the file using loadArray.

import java.io.*;
class Person implements Serializable //Make Person class Serializable so that its objects can be serialized.
{
    private static final long SerialVersionUID = 20L;
    String name;
    int age;
    public Person(String name,int age)
    {
        this.name = name;
        this.age = age;
    }
    public String toString()
    {
        return "Name:"+name+", Age:"+age;
    }
}
public class SerializeArray 
{
    public static void saveArray(Person[] arr)throws Exception //writes the array of Person to a file "Persons.ser"
    {
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Persons.ser"));
        os.writeObject(arr);
        os.close();
    }
    public static Person[] loadArray()throws Exception //Reads the array of Persons back from file.
    {
        ObjectInputStream oin = new ObjectInputStream(new FileInputStream("Persons.ser"));
        Person[] arr = (Person[]) oin.readObject();
        oin.close();
        return arr;
    }
    public static void main(String[] args) throws Exception
    {
        Person[] arr= new Person[3];
        for (int i = 0 ; i < arr.length ; i++)
        {
            arr[i] = new Person("Person"+i,25+i);
        }
        System.out.println("Saving array to file");
        saveArray(arr);
        System.out.println("Reading array back from file");
        Person[] per = loadArray();
        for (Person p : per)
        {
            System.out.println(p);
        }
    }
}

UPDATE
To incorporate this concept in your program you should first change your Entry class declaration as something like this:

public class Entry implements java.io.Serializable

And then change your doSave() method as follows:

public void doSave() throws Exception {
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("contacts.txt"));
        os.writeObject(entryList);
        os.close();
    }

And then change your doLoad() method as follows:

public void doLoad() throws Exception {
    if (length != 0) {
        //throw new Exception ("I'm not empty"); 
        //File c = new File ("contacts.txt");//No need to access the File here..
        Scanner input = new Scanner(c);
        while (input.hasNextLine()) {
            Entry e = new Entry();
            e.name = input.next();
            if ("q".equalsIgnorecase(e.name))
            break;
            e.number = input.next();
            e.notes = input.next();
            doAddEntry(e);
        }
        doAddEntry(null);
    }   
}

And change your doAddEntry method as follows:

public void doAddEntry(Entry entry) throws Exception {
    if (entry == null)
    {
      //save file here..
      doSave(); 
    }
    else if (length == 200) {
    //save file here..
    doSave(); 
    throw new Exception("I'm full");
   }
   else
   {
    boolean matched = false;
    for (int i = 0; i<length; i++) {
    if (entryList[i].name.compareToIgnoreCase(entry.name) == 0) {
      matched = true;
      break;
    }
    if(!matched)
    {
      entryList[entryList.length] = entry;
    }
   }
}

}

Ad
source: stackoverflow.com
Ad