实用代码块记录6
2016-07-08 22:58
253 查看
序列化保存工具
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import android.text.TextUtils; /** * 序列化保存工具 */ public class SerializeUtils { /** * 保存序列化对象 * * @param filePath * 保存路径 * @param obj * 序列化对象 */ public static void saveObject(String filePath, Serializable obj) { if (obj == null) { return; } File file = new File(filePath); if (file.exists()) { file.delete(); } DataOutputStream dos = null; ObjectOutputStream oos = null; try { dos = new DataOutputStream(new FileOutputStream(file)); oos = new ObjectOutputStream(dos); oos.writeObject(obj); } catch (Exception e) { file.delete(); } finally { if (dos != null) { try { dos.close(); } catch (Exception e) { } } if (oos != null) { try { oos.close(); } catch (Exception e) { } } } } /** * 读取序列化对象 * * @param filePath * 保存路径 * @return 序列化对象 */ public static Object readObject(String filePath) { if (TextUtils.isEmpty(filePath)) { return null; } File file = new File(filePath); DataInputStream dis = null; ObjectInputStream ois = null; Object obj = null; try { dis = new DataInputStream(new FileInputStream(file)); ois = new ObjectInputStream(dis); obj = ois.readObject(); } catch (Exception e) { } finally { if (dis != null) { try { dis.close(); } catch (IOException e) { } } if (ois != null) { try { ois.close(); } catch (IOException e) { } } } return obj; } /** * 删除保存文件 * * @param filePath * 保存路径 */ public static void removeObject(String filePath) { File file = new File(filePath); file.delete(); } }
相关文章推荐
- 实用代码块记录5
- Rendering Transparent 3D Surfaces in WPF with C#(转载)
- 实用代码块记录4
- Eclipse搭建Java Swing可视化开发环境
- Java中Volatile关键字详解
- JAVA 菜单设置快捷键
- Eclipse常用快捷键
- 异曲同工之妙之java虚拟机和php内核
- MATLAB中help与doc的区别
- 实用代码块记录3
- 使用Intent在活动之间穿梭(《第一行代码》读书笔记)
- C#调用Java方法
- 实用代码块记录2
- H.264之编码格式-封装成MP4格式-视频流 RTP封包
- php rabbitmq操作类及生产者和消费者实例代码
- HDU-4919-数学推导加Java大数
- java web 开发 购物车功能的实现
- sublime 安装关于lua的插件
- cmath module(针对复数)
- 【训练题】拓扑排序