zoukankan      html  css  js  c++  java
  • Java将对象写入文件读出——序列化与反序列化

    Java类中对象的序列化工作是通过ObjectOutputStream和ObjectInputStream来完成的。

    写入:

     1         File aFile=new File("e:\\c.txt");
     2         Stu a=new Stu(1, "aa", "1");
     3         FileOutputStream fileOutputStream=null;
     4         try {
     5             fileOutputStream = new FileOutputStream(aFile);
     6             ObjectOutputStream objectOutputStream=new ObjectOutputStream(fileOutputStream);
     7             objectOutputStream.writeObject(a);
     8             objectOutputStream.flush();
     9             objectOutputStream.close();
    10         } catch (FileNotFoundException e) {
    11             // TODO Auto-generated catch block
    12             e.printStackTrace();
    13         } catch (IOException e) {
    14             // TODO Auto-generated catch block
    15             e.printStackTrace();
    16         }finally {
    17             if(fileOutputStream!=null)
    18             {
    19                 try {
    20                     fileOutputStream.close();
    21                 } catch (IOException e) {
    22                     // TODO Auto-generated catch block
    23                     e.printStackTrace();
    24                 }            
    25             }
    26         }    

    读取:

    1          FileInputStream fileInputStream=new FileInputStream(aFile);
    2             ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
    3             Stu s=(Stu)objectInputStream.readObject();
    4             System.out.println(s);

    注意:

    对于任何需要被序列化的对象,都必须要实现接口Serializable,它只是一个标识接口,本身没有任何成员,只是用来标识说明当前的实现类的对象可以被序列化。

    如果在类中的一些属性,希望在对象序列化过程中不被序列化,使用关键字transient标注修饰就可以。当对象被序列化时,标注为transient的成员属性将会自动跳过。如果一个可序列化的对象包含某个不可序列化对象的引用,那么序列化操作会失败,会抛出NotSerializableException异常,那么将这个引用标记transient,就可以序列化了。
    当一个对象被序列化时,只保存对象的非静态成员变量,不能保存任何的成员方法,静态的成员变量。 
    如果一个对象的成员变量是一个对象,那么这个对象的数据成员也会被保存还原,而且会是递归的方式。 

    人生如水,不争高山,自然愈下,三年又三年。——struggle!
  • 相关阅读:
    在项目中运用到的导航高亮
    【转载】IE8 inlineblock容器不撑开问题(利用重绘解决)
    我的博客正式开通
    【转载】响应式网页设计的9条基本原则
    一款不错的在线SVG制作工具
    【转载】前端不为人知的一面前端冷知识集锦
    11.3 Daily Scrum
    11.11 Daily Scrum
    11.7 Daily Scrum(周末暂停两天Daily Scrum)
    11.12 Daily Scrum(保存草稿后忘了发布·····)
  • 原文地址:https://www.cnblogs.com/PersistWp/p/7375774.html
Copyright © 2011-2022 走看看