代码改变世界

转:java 保存对象到文件,读取文件中的对象

2013-06-29 23:57  嘻哈路飞  阅读(2470)  评论(0编辑  收藏  举报

java 保存对象到文件,读取文件中的对象       

        分类:            Java2066人阅读评论(0)收藏举报

老师布置的一个作业:

画图软件,可以将图形保存、打开

 

写一下如何将java对象保存到文件中

----------------------------------------------------------------------------------------------------------------

1、要保存的对象必须实现Serializable接口

2、

  1. privatevoid save(String path){  
  2.         FileOutputStream fos = null
  3.         ObjectOutputStream oos = null
  4.         File f = new File(path); 
  5.         try
  6.             fos = new FileOutputStream(f); 
  7.             oos = new ObjectOutputStream(fos); 
  8.             oos.writeObject(javaObject);    //括号内参数为要保存java对象 
  9.         } catch (FileNotFoundException e) { 
  10.             e.printStackTrace(); 
  11.         } catch (IOException e) { 
  12.             e.printStackTrace(); 
  13.         }finally
  14.             try
  15.                 oos.close(); 
  16.                 fos.close(); 
  17.             } catch (IOException e) { 
  18.                 e.printStackTrace(); 
  19.             } 
  20.         }    
  21.     } 
  22.      
  23.     privatevoid open(String path){ 
  24.         FileInputStream fis = null
  25.         ObjectInputStream ois = null;    
  26.         File f = new File(path); 
  27.         try
  28.             fis = new FileInputStream(f); 
  29.             ois = new ObjectInputStream(fis); 
  30.             javaObject object = (javaObject)ois.readObject();//强制类型转换 
  31.             myPanel.repaint(); 
  32.              
  33.         } catch (FileNotFoundException e) { 
  34.             e.printStackTrace(); 
  35.         } catch (IOException e) { 
  36.             e.printStackTrace(); 
  37.         } catch (ClassNotFoundException e) { 
  38.             e.printStackTrace(); 
  39.         }finally
  40.             try
  41.                 ois.close(); 
  42.                 fis.close(); 
  43.             } catch (IOException e) { 
  44.                 e.printStackTrace(); 
  45.             } 
  46.         } 
  47.     }