码迷,mamicode.com
首页 > 编程语言 > 详细

Java序列简单使用

时间:2014-09-29 11:39:40      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:blog   io   os   使用   ar   java   sp   div   on   

package javatest;

import java.io.*;

public class SerializableTest implements Serializable {
	public static class Test implements Serializable {
		private int width;
		private int height;

		public void setWidth(int width) {
			this.width = width;
		}

		public void setHeight(int height) {
			this.height = height;
		}
	}

	public static void write(Object obj, String path) {
		try {
			File f=new File(path);
		       if(f.exists()){
		           f.delete();
		       }
		       
			FileOutputStream fs = new FileOutputStream(path);
			ObjectOutputStream os = new ObjectOutputStream(fs);
			os.writeObject(obj);
			os.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static Object read(String path) throws IOException,
			ClassNotFoundException {
		FileInputStream fs = new FileInputStream(path);
		ObjectInputStream os = new ObjectInputStream(fs);
		return os.readObject();
	}

	public static void main(String[] args) throws ClassNotFoundException, IOException {
		Test test = new Test();
		test.setWidth(50);
		test.setHeight(30);
		
		String path = "ser.file";
		write(test, path);
		Test test1 = (Test)read(path);
		System.out.println(test1.height);
	}
}

 

Java序列简单使用

标签:blog   io   os   使用   ar   java   sp   div   on   

原文地址:http://www.cnblogs.com/chengxin1982/p/3999597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!