Question

I have created an object that i then added into an ArrayList. I then saved this arraylist into a .dat file using ObjectOutputStream. I know that the object has been created correctly because the next screen in the program loads directly from the object and the object can be read correctly from the file afterwards. The issue I am running into is that it appears that the object is saving, but it is not willing to be edited. Instead of editing the object in the arraylist, it is creating a new object and saving it again each time.

The code below shows the save function that is performed every time someone finishes the last screen. I am trying to make it so it will check to see if the student exists already in the array, and if so just edit the object. If the student doesn't exist, I want it to take selectedStudent (the object used for all GUI functions) and add it to the array "students" and write the array to the file, overwriting all previous data.

    @SuppressWarnings("unchecked")
public static void saveNew() throws ClassNotFoundException, IOException{
    int exists = -1;
    try{
        FileInputStream fis = new FileInputStream("records.dat");
        ObjectInputStream in = new ObjectInputStream(fis);

        students = (ArrayList<Student>) in.readObject();
        in.close();
        fis.close();
    }
    catch(IOException e){
        e.printStackTrace();
    } 
    try{
        FileOutputStream fos = new FileOutputStream("records.dat", false);
        ObjectOutputStream out = new ObjectOutputStream(fos);

        for(int i = 0; i<students.size(); i++){
            if(students.get(i).getID().equals(selectedStudent.getID())){
                exists = i;
            }
        }
        if(exists<0){
            students.add(selectedStudent);
        }
        else{
            students.set(i, selectedStudent);
        }


        out.writeObject(students);
        out.close();
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

Edit: I noticed that the variable exists was not being used to search for the object which was mistake number one, but I still have the issue where the saved object will not be changed until the method is called a second time. It seems to find it when it is run again, but when it is run the first time it will just create a new student with the edited name.

For example, the first student is created and saved. A second student is the created and saved. When the second student is being edited (without closing the program and restarting) it will, instead of editing the object in the file, create a new student object with the same information directly below the first. If the edit function is run a second time, the second student file is edited correctly but leaves the first as it was.

Was it helpful?

Solution

For a start I would edit these lines

if(students.get(i).getID().equals(selectedStudent.getID())){
   exists = i;
}

to

if(students.get(i).getID().equals(selectedStudent.getID())){
   System.out.println ("Got it");
   exists = i;
   break;
}

just to make sure it is working.

Also, you want to change the use of i to exists

else{
    students.set(i, selectedStudent);   // change to exists
}

OTHER TIPS

I think you must check your variables (if you're reusing any) and initialization code.

The snippet you've posted seems to be fine, so I can't find the error on it.

Here goes a quite similar code that works. I hope it helps.

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class Persistence {

    public static void main(String[] args) throws Exception {
        File f = new File("records.dat");
//      f.delete();
        if (!f.exists()){
            f.createNewFile();
        }

        Persistence p = new Persistence();
        if (p.peek() == null){
            p.init(); //persist an empty list
        }

        p.saveNew(new Student("ID1","Some Value")); //must insert
        p.saveNew(new Student("ID1","Some Other Value")); //must edit
        p.saveNew(new Student("ID2","Some Value")); //must insert

        ArrayList<Student> list = p.peek();
        System.out.println(list);
    }

    private void save(ArrayList<Student> list) throws Exception{
        FileOutputStream fos = new FileOutputStream("records.dat",false);//don't append
        ObjectOutputStream out = new ObjectOutputStream(fos); 
        out.writeObject(list);
        out.flush();
        out.close();
        fos.close();
    }

    private void init() throws Exception{
        save(new ArrayList<Student>());
    }

    private ArrayList<Student> peek() throws Exception{
        FileInputStream fis = new FileInputStream("records.dat");
        try{
            ObjectInputStream in = new ObjectInputStream(fis);
            ArrayList<Student> students = (ArrayList<Student>) in.readObject();
            return students;
        }catch(EOFException eof){
            return null;
        }finally{
            fis.close();
        }
    }

    public void saveNew(Student s) throws Exception {
        ArrayList<Student> students = peek();

        int editIndex = -1;
        for(int i=0;i<students.size();i++){
            if (students.get(i).getID().equals(s.getID())){
                editIndex = i;
                break;
            }
        }

        if (editIndex != -1){
            students.set(editIndex, s); //replace
        }else{
            students.add(s); //add
        }

        save(students);
    }
}

where

import java.io.Serializable;


public class Student implements Serializable{

    private static final long serialVersionUID = 1L;
    private String ID;
    private String s;

    public Student(String ID, String s) {
        this.ID = ID;
        this.s = s;
    }

    public String getID() {
        return ID;
    }

    public void setID(String iD) {
        ID = iD;
    }

    public String getS() {
        return s;
    }

    public void setS(String s) {
        this.s = s;
    }

    @Override
    public String toString() {
        return "Student [ID=" + ID + ", s=" + s + "]";
    }


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top