在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();
			}
		}
	}


你可能感兴趣的:(eclipse,java相关)