zoukankan      html  css  js  c++  java
  • JAVA_序列化和反序列化

    package com.kk.review;

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;

    public class SerializableTest {
    public static void main(String[] args) {
    try{
    ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("Employee"));
    Employee me=new Employee("kk",22,7788.99);
    oos.writeObject(me);
    oos.close();

    ObjectInputStream ois=new ObjectInputStream(new FileInputStream("Employee"));
    Employee review=(Employee) ois.readObject();
    System.out.println(review.getSalary());//输出0.0,这是double的初始化默认值,故没有被序列化
    }catch(IOException ioe){
    ioe.printStackTrace();
    }catch(ClassNotFoundException cfe){
    cfe.printStackTrace();
    }
    }
    }

    class Employee implements Serializable {
    private static final long serialVersionUID = 7404853604198492990L;

    private String name;

    private int age;

    private transient double salary; //transient:透明的,也就是不被序列化

    public Employee() {
    }

    public Employee(String name, int age, double salary) {
    this.name = name;
    this.age = age;
    this.salary = salary;
    }

    private void writeObject(ObjectOutputStream oos){
    System.out.println("这个方法将在序列化时前被执行,可以用来对字段操作,例如加密");
    }

    private void readObject(ObjectInputStream ois){
    System.out.println("这个方法将在反序列化时后被执行,可以用来对字段操作,例如解密");
    }

    public int getAge() {
    return age;
    }

    public void setAge(int age) {
    this.age = age;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public double getSalary() {
    return salary;
    }

    public void setSalary(double salary) {
    this.salary = salary;
    }

    }
  • 相关阅读:
    Niagara技术文档汇总
    cPickle对python对象进行序列化,序列化到文件或内存
    html = data.decode('gbk').encode('utf-8')
    用200行Python代码“换脸”
    No module named cv2
    JAVA Calendar具体解释
    千万别用模板给的list.size()巨坑
    div仿checkbox表单样式美化及功能
    动态规划0—1背包问题
    拒绝乱码:做外贸系统,打印俄文快递单时,避免俄文乱码的方法
  • 原文地址:https://www.cnblogs.com/BigIdiot/p/2281994.html
Copyright © 2011-2022 走看看