zoukankan      html  css  js  c++  java
  • JavaLearning:对象序列化

    package org.fun.io;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    
    @SuppressWarnings("serial")
    class Person implements Serializable {
    	private String name;
    	private int age;
    
    	public Person(String name, int age) {
    		this.name = name;
    		this.age = age;
    	}
    
    	public String toString() {
    		return "姓名:" + this.name + ",年龄:" + this.age;
    	}
    }
    
    public class SerializableDemo {
    	public static void main(String[] args) throws Exception {
    		Person[] per= { new Person("张三", 30), new Person("李四", 31),
    				new Person("王五", 32) };
    		ser(per);
    		Person[] p= (Person[]) dser();
    		print(p);
    	}
    
    	public static void ser(Object obj) throws Exception {
    		File file = new File("d:" + File.separator + "person.ser");
    		ObjectOutputStream oos = null;
    		oos = new ObjectOutputStream(new FileOutputStream(file));
    		oos.writeObject(obj);
    		oos.close();
    	}
    
    	@SuppressWarnings("resource")
    	public static Object dser() throws Exception {
    		Object temp = null;
    		File file = new File("d:" + File.separator + "person.ser");
    		ObjectInputStream ois = null;
    		ois = new ObjectInputStream(new FileInputStream(file));
    		temp = ois.readObject();
    		return temp;
    	}
    
    	public static void print(Person per[]) {
    		for (Person p : per) {
    			System.out.println(p);
    		}
    	}
    }
    

  • 相关阅读:
    菜鸟小结
    计算几何题目整理(转)
    poj 3299 Humidex
    基于C的文件操作(转)
    poj 1328 Radar Installation
    poj 1321 棋盘问题(dfs)
    poj 3302 Subsequence
    C# 资产(Property) 与普通字段(field)变量的区别
    Jumping into Cloud, Be Sure You Know How to Get Out
    关于语言的想法。
  • 原文地址:https://www.cnblogs.com/javafly/p/6037245.html
Copyright © 2011-2022 走看看