栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java对象序列号到磁盘File文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java对象序列号到磁盘File文件

java对象序列号到磁盘File文件 序列表java对象到磁盘
// 序列化
	public static void writeObject(String ai, Object obj) {
		File file = new File(MqConstant.MAP_SYS_PARAMS.get(MqConstant.ERROR_DATA_DIR) + "/" + ai);
		// 判断文件是否存在
		boolean isExist = false;
		if (file.exists()) {
			isExist = true;
		}
		FileOutputStream os = null;
		ObjectOutputStream oos = null;
		try {
			os = new FileOutputStream(file, true);
			oos = new ObjectOutputStream(os);
			// 如果文件存在则截断streamheader;若文件不存在则保留streamheader
			if (isExist) {
				long pos = os.getChannel().position() - 4;
				os.getChannel().truncate(pos);
			}
			oos.writeObject(obj);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != oos) {
				try {
					oos.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			if (null != os) {
				try {
					os.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
	}
反序列化
// 反序列化
	public static List readObjects(String ai) {
		File file = new File(MqConstant.MAP_SYS_PARAMS.get(MqConstant.ERROR_DATA_DIR) + "/" + ai);
		if (!file.exists()) {
			return null;
		}
		List list = new ArrayList();
		FileInputStream is = null;
		ObjectInputStream ois = null;
		try {
			is = new FileInputStream(file);
			ois = new ObjectInputStream(is);
			while (is.available() > 0) {
				list.add((ErrorMessage) ois.readObject());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != ois) {
				try {
					ois.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			if (null != is) {
				try {
					is.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		return list;
	}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1035520.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号