java 序列化保存到磁盘的相关问题
package com.taskManager.connectionStation;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.Date;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import com.taskManager.connectionStation.taskstation.TaskModel;/** * 对对象的保存操作 * * @author Sammor * @date 2011-1-9 */public class TaskSaveOrReadUtil<T> {private static Log log = LogFactory.getLog(TaskSaveOrReadUtil.class);private FileOutputStream fos;private ObjectOutputStream oos;private FileInputStream fis;private ObjectInputStream ois;private static String filePath = "d:/taskStroeMap.txt";public TaskSaveOrReadUtil() {// init(); }public TaskSaveOrReadUtil(String path) {this.filePath = path; //init();}/** * 这里面不可以同时取到入流和出流 */private void init() {try {fos = new FileOutputStream(filePath);fis = new FileInputStream(filePath);oos = new ObjectOutputStream(fos);ois = new ObjectInputStream(fis);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}// 序列化对象到文件public static void serialize() {try {ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));TaskModel tm = new TaskModel();tm.setTargetErtuAddress("192.168.0.1");tm.setApplyDataType(1);tm.setTaskBeginTime(new Date());tm.setTaskEndTime(new Date());tm.setTaskType(1);tm.getMapTest().put("hello", "world");out.writeObject(tm); // 序列化一个会员对象out.close();} catch (Exception x) {System.out.println(x.toString());}}// 从文件反序列化到对象public static void deserialize() {try {// 创建一个对象输入流,从文件读取对象ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));TaskModel user = (TaskModel) (in.readObject());System.out.println(user.getMapTest().get("hello"));in.close();} catch (Exception x) {System.out.println(x.toString());}}public void saveObject(T o) {ObjectOutputStream out = null;try {out = new ObjectOutputStream(new FileOutputStream(filePath));out.writeObject(o);} catch (IOException e) {throw new RuntimeException("保存文件到磁盘出错");} finally {try {out.close();} catch (IOException e) {throw new RuntimeException("关闭流出错");}}System.out.println("写入成功");}public T readObject() {T t = null;try {ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));t = (T) in.readObject();} catch (IOException e) {e.printStackTrace();log.warn("取不到本地信息文件");return null;} catch (ClassNotFoundException e) {e.printStackTrace();}return t;}public static void main(String[] args) {TaskSaveOrReadUtil ts = new TaskSaveOrReadUtil();// TaskSaveOrReadUtil.serialize();// TaskSaveOrReadUtil.deserialize();// TaskModel tm = new TaskModel();// tm.setApplyDataType(1);// ts.saveObject(tm);//TaskModel tt = (TaskModel) ts.readObject();System.out.println(tt.getApplyDataType());}}