• 序列化和反序列化


    将内存中的数据持久化到硬盘---序列化

    将硬盘上的数据持久化到内存---反序列化

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace D_003
    {
       [Serializable]//证明这个类是可被序列化的(类)
       public  class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace D_003
    {
        class Program
        {
            static void Main(string[] args)
            {
                #region 序列化
                //List<Person> list = new List<Person>();
                //Person p = new Person();
                //p.Name = "小明";
                //p.Age = 12;
                //list.Add(p);
                ////序列化器  二进制序列化器
                //BinaryFormatter bf = new BinaryFormatter();
                //Stream stream = new FileStream("save.bin", FileMode.Create);
                //bf.Serialize(stream, list);
                //stream.Close();
                //Console.WriteLine("Ok"); 
                #endregion
                #region 反序列化
                Stream fs = new FileStream("save.bin",FileMode.Open);
                BinaryFormatter bf = new BinaryFormatter();
                List<Person> list = (List<Person>)bf.Deserialize(fs);
                foreach (Person item in list)
                {
                    Console.WriteLine(item.Name+""+item.Age);
                }
                fs.Close();
                #endregion
                Console.ReadKey();
            }
        }
    }

     对象序列化

    (1).对象序列化,就是将Object转换成byte序列,反之叫对象的反序列

    (2).序列化流(ObjectOutStream),是过滤器----writeObject

         反序列化流(ObjectInPutStream)---readObject

    (3).序列化接口(Serializable)

    对象必须实现序列化接口,才能进行序列化,否则将会出现异常

    这个接口,没有任何方法,只是一个标准

    (4).对象序列化就是保存对象

    实际作用

    序列化相当于加密,反序列化相当于解密,作用是方便储存和传输

    序列化 (Serialization)将对象的状态信息转换为可以存储或传输的形式的过程。在序列化期间,对象将其当前状态写入到临时或持久性存储区。以后,可以通过从存储区中读取或反序列化对象的状态,重新创建该对象。

    目的

    1、以某种存储形式使自定义对象持久化
    2、将对象从一个地方传递到另一个地方。
    3、使程序更具维护性。
     
    案例
    对象序列化
    package cn.happy.com;
    
    import java.io.Serializable;
    
    /**
     * 对student对象进行序列化
     * @author CY
     *
     */
    public class Student implements Serializable{
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        private String stuno;
        private String stuname;
        private int stuage;
        public Student(String stuno, String stuname, int stuage) {
            super();
            this.stuno = stuno;
            this.stuname = stuname;
            this.stuage = stuage;
        }
        public String getStuno() {
            return stuno;
        }
        @Override
        public String toString() {
            return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage=" + stuage + "]";
        }
        public Student() {
            super();
            // TODO Auto-generated constructor stub
        }
        public void setStuno(String stuno) {
            this.stuno = stuno;
        }
        public String getStuname() {
            return stuname;
        }
        public void setStuname(String stuname) {
            this.stuname = stuname;
        }
        public int getStuage() {
            return stuage;
        }
        public void setStuage(int stuage) {
            this.stuage = stuage;
        }
    }
    package cn.happy.com;
    
    import java.io.*;
    
    public class ObjectSeriaDemo1 {
    /**
     * 对象进行保存
     * @param args
     * @throws Exception 
     * @throws FileNotFoundException 
     */
        public static void main(String[] args) throws Exception {
            //路径
            String file="demp/object.dat";
            //1.对象的序列化
            /*ObjectOutputStream oos=new ObjectOutputStream(
                    new FileOutputStream(file));
            Student stu=new Student("1001","张三",20);
            oos.writeObject(stu);
            oos.flush();
            oos.close();*/
            ObjectInputStream ois=new ObjectInputStream(
                    new FileInputStream(file));
            Student stu=(Student)ois.readObject();
            System.out.println(stu);
            ois.close();
        }
    }

     ================================================================

    package cn.happy.com;
    
    import java.io.Serializable;
    
    /**
     * 对student对象进行序列化
     * @author CY
     *
     */
    //序列化中子类和父类构造函数的调用问题
    public class Student implements Serializable{
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        private String stuno;
        private String stuname;
        private transient int stuage;
        //该元素不会进行jvm默认的序列化  也可以自己完成这个元素的序列化
        public Student(String stuno, String stuname, int stuage) {
            super();
            this.stuno = stuno;
            this.stuname = stuname;
            this.stuage = stuage;
        }
        public String getStuno() {
            return stuno;
        }
        @Override
        public String toString() {
            return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage=" + stuage + "]";
        }
        public Student() {
            super();
            // TODO Auto-generated constructor stub
        }
        public void setStuno(String stuno) {
            this.stuno = stuno;
        }
        public String getStuname() {
            return stuname;
        }
        public void setStuname(String stuname) {
            this.stuname = stuname;
        }
        public int getStuage() {
            return stuage;
        }
        public void setStuage(int stuage) {
            this.stuage = stuage;
        }
        private void writeObject(java.io.ObjectOutputStream s)
                   throws java.io.IOException{
            s.defaultWriteObject();//把jvm能默认序列化的元素进行序列化的操纵
            s.writeInt(stuage);//自己完成stuage的序列化
        }
        private void readObject(java.io.ObjectInputStream s)
                   throws java.io.IOException,ClassNotFoundException{
            s.defaultReadObject();//把jvm能默认序列化的元素进行反序列化的操纵
            this.stuage=s.readInt();//自己完成stuage的反序列化
        }
    }
    package cn.happy.com;
    
    import java.io.*;
    
    public class ObjectSeriaDemo1 {
    /**
     * 对象进行保存
     * @param args
     * @throws Exception 
     * @throws FileNotFoundException 
     */
        public static void main(String[] args) throws Exception {
            //路径
            String file="demp/object.dat";
            //1.对象的序列化
            /*ObjectOutputStream oos=new ObjectOutputStream(
                    new FileOutputStream(file));
            Student stu=new Student("1001","张三",20);
            oos.writeObject(stu);
            oos.flush();
            oos.close();*/
            ObjectInputStream ois=new ObjectInputStream(
                    new FileInputStream(file));
            Student stu=(Student)ois.readObject();
            System.out.println(stu);
            ois.close();
            //并不是所有的对象都被期望序列化
        }
    }
    package cn.happy.com;
    
    import java.io.*;
    
    public class ObjectSeriaDem02 {
        /**
         * 创建对象的时候递归调用了父类的构造函数
         * @param args
         * @throws Exception
         */
        public static void main(String[] args) throws Exception{
            /*ObjectOutputStream oos=new ObjectOutputStream(
                    new FileOutputStream("demp/object.dat"));
            Foo2 foo2=new Foo2();
            oos.writeObject(foo2);
            oos.flush();
            oos.close();*/
            //反序列化是否递归调用了父类的构造函数
            /*ObjectInputStream ois=new ObjectInputStream(
                    new FileInputStream("demp/object.dat"));
            Foo2 foo2=(Foo2)ois.readObject();
            System.out.println(foo2);
            ois.close();*/
            
            
            /*ObjectOutputStream oos=new ObjectOutputStream(
                    new FileOutputStream("demp/object.dat"));
            Bar2 bar2=new Bar2();
            oos.writeObject(bar2);
            oos.flush();
            oos.close();*/
            
            ObjectInputStream ois=new ObjectInputStream(
                    new FileInputStream("demp/object.dat"));
            Bar2 bar2=(Bar2)ois.readObject();
            System.out.println(bar2);
            ois.close();
            /**
             * 对子类对象进行反序列化操作时
             * 如果其父类没有实现序列化接口
             * 那么其父类的构造函数会被显示调用
             * 
             */
        }
    
    }
    //一个类实现了序列化接口他的子类都能实现序列化接口
    class Foo implements Serializable{
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        public Foo(){
            System.out.println("foo...");
        }
    }
    class Foo1 extends  Foo{
        public Foo1(){
        System.out.println("foo1...");
        }
    }
    class Foo2 extends Foo1{
        public Foo2(){
            System.out.println("foo2...'");
        }
    }
    class Bar{
        public Bar(){
            System.out.println("bar'");
        }
    }
    class Bar1 extends Bar implements Serializable{
        public Bar1(){
            System.out.println("bar1...");
        }
    }
    class Bar2 extends Bar1{
        public Bar2(){
            System.out.println("bar2...");
        }
    }
  • 相关阅读:
    电脑知识
    编译器错误信息: CS0433: 类型“ASP.global_asax”同时存在于“c:/WINDOWS/Microsoft.NET/Framework/v2.0.50727...的解决方法
    windows平台下的oracle ORA-01031的解决方法
    .NET下使用HTTP请求的正确姿势
    EasyUI Datagrid 分页
    Js 运算符(加减乘除)
    Navicat 运行 Oracle 存储过程示例
    oracle数据库忘记sys(或system)账户密码
    SQL Server 死锁问题
    C# 给某个方法设定执行超时时间
  • 原文地址:https://www.cnblogs.com/lcycn/p/7094562.html
Copyright © 2020-2023  润新知