Java序列简单使用

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);
	}
}
原文地址:https://www.cnblogs.com/chengxin1982/p/3999597.html