• 对象的序列化


    import java.io.Serializable;
    import java.io.*;
    
    class Data implements Serializable {
    	private int i;
    
    	Data(int x) {
    		i = x;
    	}
    
    	public String toString() {
    		return Integer.toString(i);
    	}
    }
    
    public class Worm implements Serializable {
    	private static int r() {
    		return (int) (Math.random() * 10);
    	}
    
    	private Data[] datas = { new Data(r()), new Data(r()), new Data(r()) };
    
    	private Worm next;
    	private char c;
    
    	Worm(int i, char x) {
    		System.out.println("worm constructor:" + i);
    		c = x;
    		if (--i > 0) {
    			next = new Worm(i, (char) (x + 1));
    		}
    	}
    
    	Worm() {
    		System.out.println("deault constructor");
    	}
    
    	public String toString() {
    		String s = " ";
    		for (int i = 0; i < datas.length; i++) {
    			s += datas[i].toString();
    		}
    		if (next != null) {
    			s += next.toString();
    		}
    		return s;
    	}
    
    	public static void main(String[] args) {
    		Worm w = new Worm(6, 'a');
    		System.out.println("w = " + w);
    		try {
    			ObjectOutputStream out = new ObjectOutputStream(
    					new FileOutputStream("worm.out"));
    			out.writeObject("Worm storage");
    			out.writeObject(w);
    			out.close(); // Also flushes output
    			ObjectInputStream in = new ObjectInputStream(new FileInputStream(
    					"worm.out"));
    			String s = (String) in.readObject();
    			Worm w2 = (Worm) in.readObject();
    			System.out.println(s + ", w2 = " + w2);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		try {
    			ByteArrayOutputStream bout = new ByteArrayOutputStream();
    			ObjectOutputStream out = new ObjectOutputStream(bout);
    			out.writeObject("Worm storage");
    			out.writeObject(w);
    			out.flush();
    			ObjectInputStream in = new ObjectInputStream(
    					new ByteArrayInputStream(bout.toByteArray()));
    			String s = (String) in.readObject();
    			Worm w3 = (Worm) in.readObject();
    			System.out.println(s + ", w3 = " + w3);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    
    }
    

      

  • 相关阅读:
    Oracle创建自增字段方法-ORACLE SEQUENCE的简介
    iOS项目开发实战——使用Xcode6设计自己定义控件与图形
    准备开源用javascript写Tomcat下的WebApp的项目
    Codeforces Round #256 (Div. 2) B. Suffix Structures
    静默方式安装10g数据库软件+升级patch+手工建库
    oracle 数据库开发面试题
    待机异常篇
    HTTP状态码(HTTP Status Code)
    POJ3126——Prime Path
    RHEL7 -- 通过gerp使用正则表达式
  • 原文地址:https://www.cnblogs.com/chuiyuan/p/4349735.html
Copyright © 2020-2023  润新知