转:java 保存对象到文件,读取文件中的对象
2013-06-29 23:57 嘻哈路飞 阅读(2470) 评论(0) 编辑 收藏 举报java 保存对象到文件,读取文件中的对象
老师布置的一个作业:
画图软件,可以将图形保存、打开
写一下如何将java对象保存到文件中
----------------------------------------------------------------------------------------------------------------
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();
- }
- }
- }