对象保存为文件操作类 ObjectFileUtil

来源:互联网 发布:特效摄影软件下载 编辑:程序博客网 时间:2024/04/28 20:03

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ObjectFileUtil {
 private static Log log = LogFactory.getLog(ObjectFileUtil.class);

 public static boolean objectToFile(String filePath, Object obj)
 {
  boolean result = false;
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;
  try {
   fos = new FileOutputStream(filePath);
   oos = new ObjectOutputStream(fos);
   oos.writeObject(obj);
   result = true;
  } catch (Exception e) {
   // TODO: handle exception
   log.error(e);
  }finally{
   if (oos!=null)
    try {
     oos.close();
    } catch (IOException e1) {
     // TODO Auto-generated catch block
     log.error(e1);
    }
   if (fos!=null)
    try {
     fos.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     log.error(e);
    }
  }
  
  return result;
 }
 public static Object fileToObject(String filePath)
 {
  Object obj= null;
  FileInputStream fis = null;
  ObjectInputStream ois = null;
  try {
   fis = new FileInputStream(filePath);
   ois = new ObjectInputStream(fis);
   obj = ois.readObject();
  } catch (Exception e) {
   // TODO: handle exception
   log.error(e);
  }finally{
   if (ois!=null)
    try {
     ois.close();
    } catch (IOException e1) {
     // TODO Auto-generated catch block
     log.error(e1);
    }
   if (fis!=null)
    try {
     fis.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     log.error(e);
    }
  }
  return obj;
 }
}