Java对象的序列化与反序列化


1. 对象需要实现 Serializable接口(并且该对象的成员也需要implements Serializable)


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.zyh.jwc.domain.CachePicItem;

/**
 * 操作java对象序列化
 */
public class MyObjectUtils {

	public static void setObjectToDisk(CachePicItem object, File file) {
		System.out.println(object.getList().toString());
		try {
			FileOutputStream fos = new FileOutputStream(file);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(object);
			oos.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static CachePicItem getObjectFromDisk(File file) {
		CachePicItem object = new CachePicItem();
		try {
			FileInputStream fis = new FileInputStream(file);
			ObjectInputStream ois = new ObjectInputStream(fis);
			object = (CachePicItem) ois.readObject();
			ois.close();
			System.out.println(object.getList().toString());
			return object;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
}