• Java学习笔记【十一、序列化】


    序列化的条件

    • 实现Serializable接口
    • 所有属性必须是可序列化的,或标记为transient(不做序列化)

    序列化-将对象输出为序列化文件

    ObjectOutputStream

    反序列化-将序列化结果读取为对象

    ObjectInputStream

        import java.io.FileInputStream;
        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.io.ObjectInputStream;
        import java.io.ObjectOutputStream;
    
        public class InputOutputStream {
    
        public static void main(String[] args) {
    	// TODO Auto-generated method stub
    	People p = new People();
    	p.name = "Tom";
    	p.age = 18;
    	p.sex = "female";
    	p.num = 12321;
    
    	String path = "E:/JavaFile/tempFile/p.ser";
    
    	try {
    		FileOutputStream fileOut = new FileOutputStream(path);
    		ObjectOutputStream out = new ObjectOutputStream(fileOut);
    		out.writeObject(p);
    		out.close();
    		fileOut.close();
    		System.out.println("Write complete");
    
    		People p2 = new People();
    		FileInputStream fileIn = new FileInputStream(path);
    		ObjectInputStream in = new ObjectInputStream(fileIn);
    		p2 = (People) in.readObject();
    		p2.Print();
    		in.close();
    		fileIn.close();
    	} catch (FileNotFoundException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	} catch (IOException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	} catch (ClassNotFoundException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    
        }
    
        }
    
    class People implements java.io.Serializable {
    String name;
    int age;
    String sex;
    transient int num;// 序列化后该属性未在序列化结果中,所以反序列化后该属性无值
    
    void Print() {
    	System.out.println("name:" + name + ",age:" + age + ",sex:" + sex + ",num:" + num);
    }
    }
  • 相关阅读:
    每日总结3.8
    Go中定时器实现原理及源码解析
    Go语言实现布谷鸟过滤器
    详解Go语言调度循环源码实现
    Go语言中时间轮的实现
    详解Go语言I/O多路复用netpoller模型
    详解Go中内存分配源码实现
    Go中由WaitGroup引发对内存对齐思考
    【分享】java精品实战教程
    nginx实战教程
  • 原文地址:https://www.cnblogs.com/shanelau/p/6493244.html
Copyright © 2020-2023  润新知