序列化与反序列化I 浅谈

import java.io.Serializable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
/**
 * Java序列化是不能序列化static变量的
 * 序列化反序列化方案
 * 1 - 修饰符 static和transient
 * 2 - readObject和writeObject方法
 * 3 - Serializable 接口 不重写也可以操作序列,反序列。(性能较低占用空间可能偏大,但是使用频率高)
 * 4 - Externalizable接口 重写readExternal和writeExternal方法(决定保存对象,速度高,但是使用频率低)
 */
public class 序列化与反序列化 {
    static class Person implements Serializable {
        /**
         *
         */
        private static final long serialVersionUID = 1L;
        private String name;
        private int age;

        public static String test = "IBM";

        public String getName() {
            return name;
        }

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

        public int getAge() {
            return age;
        }

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

        public static void main(String[] args) {

            Person person = new Person();
//            person.setAge(25);
//            person.setName("YXY");
            //Person.test = "JAVA"; //modify the test value

            File file = new File("/Users/christopoher/Desktop/book");
            //序列化
            try {
                OutputStream out = new FileOutputStream(file);
                ObjectOutputStream objout = new ObjectOutputStream(out);
                objout.writeObject(person);
                objout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //code segment 1
            Person perobj = null;
            // 反序列化
            try {
                InputStream in = new FileInputStream(file);
                ObjectInputStream objin = new ObjectInputStream(in);
                perobj = (Person) objin.readObject();//恢复流中的非静态和非瞬态字段
                System.out.println(perobj.test);
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值