Search code examples
javafile-iofileinputstreamobjectoutputstreamfile-access

Saving Objects to File. Custom methods to add/remove Object


I want to be able to save the objects created in my program to a file. I have watched a few tutorials on ObjectOutputStream, but the problem is, they only show how to save a specific object created in the main method. What I want, I that the program automatically saves every created object. Taking the Group Object in my program as an example. This is the add method:

public void addGroup(int gid, String groupname) {
    Group newgroup = new Group(gid, groupname);
    if (!Groups.contains(newgroup)) {
        Groups.add(newgroup);
        return;
    }else
        JOptionPane.showMessageDialog(null, "Group with ID " + gid
                + " already exists!", "Error",
                JOptionPane.WARNING_MESSAGE);
}

It is part of my database class. I wan to automatically save every created group to the file. How would this be done? where do I declare the new file, in the database class? in the main method?

My second question is, if I delete a group, using the remove method:

public void removeGroup(int gid) {

    if (!Groups.remove(new Group(gid, null))) {
        JOptionPane.showMessageDialog(null, "Group with ID[" + gid
                + "] not present. System unchanged.");
    }

}

How do I delete it from the file? I know, that I cant really delete an Object from the file, but how will I blank out the space?

Thanks in advance for all the help :)


Solution

  • If you have access to 3rd party libraries, just use XStream to serialize to XML. If not, you can serialize and save.

    Follow a serialization tutorial like this: http://www.tutorialspoint.com/java/java_serialization.htm

    I don't think you want to try to remove anything from the file.. just rewrite it when you make a change. Make a couple methods to read in the file and also to serialize objects and save to file. Here is an example

    Group.java

    import java.io.Serializable;
    
    public class Group implements Serializable
    {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    private String guid;
    private String groupName;
    
    public Group(String guid, String groupName) {
        super();
        this.guid = guid;
        this.groupName = groupName;
    }
    
    public String getGuid() {
        return guid;
    }
    public void setGuid(String guid) {
        this.guid = guid;
    }
    public String getGroupName() {
        return groupName;
    }
    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }
    }
    

    GroupData.java

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.util.ArrayList;
    
    public class GroupData extends ArrayList<Group>
    {
    private static final long serialVersionUID = 1L;
    
    public GroupData(){}
    
    public void addGroup(Group group)
    {
        this.add(group);
        saveGroupData();
    }
    
    public void removeGroup(Group group)
    {
        this.remove(group);
        saveGroupData();
    }
    
    public void saveGroupData()
    {
          try
          {
             FileOutputStream fileOut = new FileOutputStream("C:\\Users\\tester\\group-data.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut);
    
             out.writeObject(this);
    
             out.close();
             fileOut.close();
          }
          catch(IOException i)
          {
              i.printStackTrace();
          }
    }
    
    public void loadGroupData()
    {
          try
          {
             FileInputStream fileIn = new FileInputStream("C:\\Users\\tester\\group-data.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn);
             GroupData tmp = (GroupData) in.readObject();
    
             this.clear();
             this.addAll(tmp);
    
             in.close();
             fileIn.close();
          }
          catch(IOException i)
          {
             i.printStackTrace();
             return;
          }
          catch(ClassNotFoundException c)
          {
             c.printStackTrace();
             return;
          }
    }
    }
    

    Here is a test

    TestGroup.java

    public class TestGroup {
    
    /**
     * @param args
     */
    public static void main(String[] args) 
    {
    
        Group group1 = new Group("123", "testers");
        Group group2 = new Group("456", "programmers");
        Group group3 = new Group("687", "students");
    
        GroupData groupData = new GroupData();
    
        groupData.add(group1);
        groupData.add(group2);
        groupData.add(group3);
    
        groupData.remove(group3);
    }
    
    }