zoukankan      html  css  js  c++  java
  • 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);
    }
    }
  • 相关阅读:
    http://www.codeplex.com/ 一个不错的开源网站
    阳光灿烂每一天z
    Mercurial使用简单介绍zz
    德国人的记事本 zz
    你一定要知道的71个做饭技巧
    推荐一个原型设计软件 Balsamiq Mockups
    不能一起吃的食物
    雷电预防
    马云 + 史玉柱的40条经典语录zz
    (转)扩展ArcGIS API for Silverlight/WPF 中的TextSymbol支持角度标注
  • 原文地址:https://www.cnblogs.com/shanelau/p/6493244.html
Copyright © 2011-2022 走看看