package com.yuyh.library.utils; import com.yuyh.library.utils.io.IOUtils; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * 序列化工具类 * * @author yuyh. * @date 16/4/10. */ public class SerializeUtils { private SerializeUtils() { throw new AssertionError(); } /** * 从文件中反序列化对象 * * @param filePath * @return */ public static Object deserialization(String filePath) { ObjectInputStream in = null; try { in = new ObjectInputStream(new FileInputStream(filePath)); Object o = in.readObject(); in.close(); return o; } catch (FileNotFoundException e) { throw new RuntimeException("FileNotFoundException occurred. ", e); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException occurred. ", e); } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { IOUtils.close(in); } } /** * 序列化对象到文件中 * * @param filePath * @param obj */ public static void serialization(String filePath, Object obj) { ObjectOutputStream out = null; try { out = new ObjectOutputStream(new FileOutputStream(filePath)); out.writeObject(obj); out.close(); } catch (FileNotFoundException e) { throw new RuntimeException("FileNotFoundException occurred. ", e); } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { IOUtils.close(out); } } }