java序列化

序列化操作

  • 该类必须实现java.io.Serializable 接口,Serializable 是一个标记接口,不实现此接口的类将不会使任何状态序列化或反序列化,会抛出NotSerializableException

  • 该类的所有属性必须是可序列化的。如果有一个属性不需要可序列化的,则该属性必须注明是瞬态的,使用transient 关键字修饰。

  • public class Employee implements java.io.Serializable {
        public String name;
        public String address;
        public transient int age; // transient瞬态修饰成员,不会被序列化
        public void addressCheck() {
              System.out.println("Address  check : " + name + " -- " + address);
        }
    }

    2.写出对象方法

    • public final void writeObject (Object obj)` : 将指定的对象写出。

    • public class SerializeDemo{
             public static void main(String [] args)   {
              Employee e = new Employee();
              e.name = "zhangsan";
              e.address = "beiqinglu";
              e.age = 20; 
              try {
                    // 创建序列化流对象
                ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.txt"));
                  // 写出对象
                  out.writeObject(e);
                  // 释放资源
                  out.close();
                  fileOut.close();
                  System.out.println("Serialized data is saved"); // 姓名,地址被序列化,年龄没有被序列化。
              } catch(IOException i)   {
                  i.printStackTrace();
              }
             }
      }
      输出结果:
      Serialized data is saved

      反序列化操作1

      如果能找到一个对象的class文件,我们可以进行反序列化操作,调用ObjectInputStream读取对象的方法:

      • public final Object readObject () : 读取一个对象。

      • public class DeserializeDemo {
           public static void main(String [] args)   {
                Employee e = null;
                try {        
                     // 创建反序列化流
                     FileInputStream fileIn = new FileInputStream("employee.txt");
                     ObjectInputStream in = new ObjectInputStream(fileIn);
                     // 读取一个对象
                     e = (Employee) in.readObject();
                     // 释放资源
                     in.close();
                     fileIn.close();
                }catch(IOException i) {
                     // 捕获其他异常
                     i.printStackTrace();
                     return;
                }catch(ClassNotFoundException c)  {
                    // 捕获类找不到异常
                     System.out.println("Employee class not found");
                     c.printStackTrace();
                     return;
                }
                // 无异常,直接打印输出
                System.out.println("Name: " + e.name);    // zhangsan
                System.out.println("Address: " + e.address); // beiqinglu
                System.out.println("age: " + e.age); // 0
            }
        }
原文地址:https://www.cnblogs.com/paoge/p/13602524.html