So I have been using Java for 6 months and I have come across a problem.
I have a program where you populate a hashmap through textboxes and a combobox. I also have an add button which adds the information to the hashmap. When I exit the program through the use of a menubar the hashmap is then written to a .ser file. I also have a form which a textarea to display all the data that has been populated into the hashmap.
When the program is closed the .ser has been written, but when I open the program again it does not populate the hashmap as I can no longer see the populated entries in the textarea, nor does it allow me to add data to the .ser file.
(Terrible explanation, I know)
Hopefully the code below will explain what I can't.
//Code on my main menu for file creation / reading to the hashmap
try
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("carFile.ser"));
HashMap<String, Car> cars = (HashMap<String, Car>)ois.readObject();
ois.close();
}
catch(ClassNotFoundException cnfx)
{
JOptionPane.showMessageDialog(null, "The data could not be read.");
cnfx.printStackTrace();
}
catch(FileNotFoundException fnfx)
{
JOptionPane.showMessageDialog(null, "No file found.");
fnfx.printStackTrace();
}
catch(IOException iox)
{
JOptionPane.showMessageDialog(null, "Could not read from file.");
iox.printStackTrace();
}
//Code to output data to .ser file, also on main menu
if ( s.equalsIgnoreCase("Exit"))
{
try{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("carFile.ser"));
oos.writeObject(cars);
oos.close();
}
catch(FileNotFoundException fnfx)
{
JOptionPane.showMessageDialog(null, "No file found!");
fnfx.printStackTrace();
}
catch(IOException iox)
{
JOptionPane.showMessageDialog(null, "Could not write file");
iox.printStackTrace();
}
System.exit(0);
}
//Code on Display page, which stops working after I close the program after the file has been created.
if ( e.getSource()==btnExit)
{
txtArea.setText("");
this.setVisible(false);
}
elseif ( e.getSource()==btnDisplay)
{
txtArea.setText("");
String s;
s="Reg No. Make Model Description Colour Category Mileage Year Cost(£) Selling Price(£)\n";
txtArea.append(s);
s="------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n";
txtArea.append(s);
Set set = cars.entrySet();
Iterator i = set.iterator();
while (i.hasNext())
{
Map.Entry me = (Map.Entry)i.next();
s = me.getValue() + "\n";
txtArea.append(s);
}
I have searched the intenet for hours and have not found a similar problem.
Tried the above method. I don't think the file is reading in as it is not populating the hashmap even after creating and writing to the file, once I close the program nothing displays, and it does not allow to add to the file. Tested this by using my textarea which displays all the data using an iterator