• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Attn Java Gurus

james182

Member
If I have an object that I have created, (the object has a HashMap and a map that extends HashMap as its two fields)
how do I save this object to a file and then open the program at another time and load that object from the file?
 
use an ObjectOutputStream to write your object to a file....then use an ObjectInputStream to read it in, simple as that 🙂

HTH
 
Originally posted by: jonmullen
this should help you Text

fine...
import java.io.*;
class theObject implements Serializable
...
try{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
out.writeObject(the object);
}
catch(IOException e) { blah blah }
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
theObject object = (theObject)in.readObject(); //load in the object and cast it
}
catch(IOException e) { blah blah }
 
This is what I have for my code and its not working. Does anyone see anything wrong with this:
String fn=JOptionPane.showInputDialog("Please enter the name that you wish to save the database as.");
File file=new File(fn);
try{
file.createNewFile();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
try{
oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(cdc);
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
try{
oos.close();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
 
Where / how do you declare oos and cdc? And make sure that your class implements java.io.Serializable, if you want to write it to a stream.

-Josh
 
Back
Top