1、要保存的对象必须实现Serializable接口。
2、
privatevoid save(String path){
FileOutputStream fos = null;
ObjectOutputStream oos = null;
File f = new File(path);
try {
fos = new FileOutputStream(f);
oos = new ObjectOutputStream(fos);
oos.writeObject(javaObject); //括号内参数为要保存java对象
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
privatevoid open(String path){
FileInputStream fis = null;
ObjectInputStream ois = null;
File f = new File(path);
try {
fis = new FileInputStream(f);
ois = new ObjectInputStream(fis);
javaObject object = (javaObject)ois.readObject();//强制类型转换
myPanel.repaint();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
try {
ois.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}