问题
ive looked at a few problems on this matter already but couldnt resolve my issue.
As you can see below, i save all the objects in my Patient ArrayList
(pList
- which is private at the top of the class) into the "Patient.ser" file through serialization. As far as i can tell this is working with no problems. "patSizeAtSave
" is a private variable which i am using to mark as a bound to work with when loading the file(see below)
the "patModel
" is the DefaultListModel
i use for the JLists
in my GUI
so i try to populate those lists with what has been added back to the Patient ArrayList(pList)
MY PROBLEM: When i hit the load button on the GUI
it calls the loadPatientList()
method below, but nothing is being put into my JLists so i can't tell if it works at all.
Any idea's on how to fix this?
private void savePatientList() throws FileNotFoundException {
try
{
FileOutputStream fs = new FileOutputStream("Patient.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
for(Patient p: pList)
{
os.writeObject(p);
}
fs.close();
os.close();
patSizeAtSave = pList.size();
JOptionPane.showMessageDialog(jTabPane, "Save Complete!", "Notification", JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void loadPatientList()
{
FileInputStream fs;
ObjectInputStream is;
try
{
fs = new FileInputStream("Patient.ser");
is = new ObjectInputStream(fs);
for(int i = 0; i < patSizeAtSave; i++)
{
Patient p = (Patient) is.readObject();
pList.add(p);
patModel.addElement(p.getPNo() + ": " + p.getPName());
}
jListPatient.setModel(patModel);
jListPatient2.setModel(patModel);
fs.close();
is.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
回答1:
Did you try to load you patients list in the same JVM (without exiting the JVM) after saving it ? Because if you exit your JVM before reloading you patients list, your patSizeAtSave will be reset to 0 (since it is not saved to any file/persitent storage) but only in memory. When you will call loadPatientList in a new JVM, your for loop will not load any patient since patSizeAtSave is 0.
You should rather save the whole list pList (assuming you use a Serializable implementation of List, sucha as ArrayList / LinkedList), like this :
FileOutputStream fs = new FileOutputStream("Patient.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(pList);
And load it back with :
pList = (List<Patient>) is.readObject();
for(Patient p: pList)
{
patModel.addElement(p.getPNo() + ": " + p.getPName());
}
This way, the list size will also be saved in you serialized file.
Regards
来源:https://stackoverflow.com/questions/15684586/how-to-load-a-serialized-file-back-to-an-arraylist