在java中使用kryo框架来实现高效序列化与反序列化

最近因为项目需要,需要做一些javabean方面的序列化与反序列化,在重重对比之下,决定选用kryo框架,至于为什么选用该框架(肯定是高效呗),在文章最后给出一些链接,大家可以看看。

我是下载到kryo2.21源码之后,重新打包成jar包使用的,kryo2.21源码下载地址:http://download.csdn.net/detail/nkliming/6554519

最后贴上这方面相关的代码

1、将所有对象序列化到文件中保存

public static void writeSerializeObjectToFile(String pathName)
			throws IOException {
		FileOutputStream fos = new FileOutputStream(pathName);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		for (int i = 0; i < statuses.size(); i++) {
			oos.writeObject(statuses.get(i));
		}
		oos.close();
		statuses.clear();
	}

2、从序列化的文件中反序列化出所有对象

public static void readSerializeObjectFromFileBykryo(String pathName)
			throws IOException {
		Kryo kryo=new Kryo();
		Input input=null;
		try {
			RandomAccessFile raf = new RandomAccessFile(pathName, "r");
			input = new Input(new FileInputStream(raf.getFD()), 65536);//BUFFERSIZE->65536
			StatusBean statusBean=null;
			System.err.println(kryo.getDepth());
			while((statusBean=(StatusBean)kryo.readObject(input, StatusBean.class))!=null){
				System.out.println(statusBean.getNickname()+"%%"+statusBean.getDatetime()+"%%"+statusBean.getLink()+"%%"+statusBean.getSource()
						+"%%"+statusBean.getTimestamp()+"%%"+statusBean.getCollectioncnt()+"%%"+statusBean.getCommentcnt()
						+"%%"+statusBean.getPrizecnt()+"%%"+statusBean.getRepostcnt()+"%%"+statusBean.getContent());
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (KryoException e) {
//			System.out.println("ok");
		}finally {
			if (input != null) {
				input.close();
			}
		}
	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值