package com.walker.infrastructure.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class ObjectStreamUtils { private static final Logger logger = LoggerFactory.getLogger(ObjectStreamUtils.class); /** * 把对象写入文件 * @param filePath * @param obj * @date 2012-7-6 */ public static void writeObjectToFile(String filePath, Object obj){ File file = new File(filePath); ObjectOutputStream oos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(file); oos = new ObjectOutputStream(fos); oos.writeObject(obj); } catch (FileNotFoundException e) { // TODO Auto-generated catch block logger.error("saveObjectToFile():File not found! filePath = " + filePath); throw new com.walker.infrastructure.core.FileNotFoundException(e); } catch (IOException e) { // TODO Auto-generated catch block logger.error("File save error!"); e.printStackTrace(); } finally { try { if(oos != null){ oos.close(); } if(fos != null){ fos.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 从文件读出对象,完成后把文件删除 * @param filePath * @return * @date 2012-7-6 */ public static Object readObjectFromFile(String filePath){ File file = new File(filePath); if(!file.exists()){ return null; } ObjectInputStream ois = null; FileInputStream fis = null; try { fis = new FileInputStream(file); ois = new ObjectInputStream(fis); file.delete(); return ois.readObject(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block logger.warn("File not found in readObject!"); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException ex){ } finally { try { if(ois != null){ ois.close(); } if(fis != null){ fis.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } }