• 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);
    		}
    	}
    }
    

  • 相关阅读:
    进制的转换
    输出蛇型矩阵
    输出弓形矩阵
    找出一个数组中出现次数最多的那个元素
    开灯问题
    find your present
    核反应堆
    Box of Bricks最小移动砖块数目
    超级楼梯
    Bootstrap中的 JavaScript 特效 — 下拉菜单和滚动监听插件
  • 原文地址:https://www.cnblogs.com/javafly/p/6037245.html
Copyright © 2020-2023  润新知