kryo的反序列化异常问题

问题描述:在使用kryo框架进行序列化时,我将list中的每个对象都writeobject,代码如下:
public static void writeSerializeObjectToFileBykryo(String pathName)
			throws IOException {
		Kryo kryo = new Kryo();
		FieldSerializer serializer = new FieldSerializer(kryo, StatusBean.class);
        kryo.register(StatusBean.class, serializer);
		Output output = null;
		try {
			RandomAccessFile raf = new RandomAccessFile(pathName, "rw");
			output = new Output(new FileOutputStream(raf.getFD()), 65536);//BUFFERSIZE->65536
			for (int i = 0; i < statuses.size(); i++) {
				kryo.writeObject(output, statuses.get(i));
			}
		} finally {
			if (output != null) {
				output.close();
			}
			statuses.clear();
		}
	}

然后,通过下面的代码,将对象反序列化,代码如下:

public static void main(String args[]){
		Kryo kryo=new Kryo();
		//Registration registration=kryo.register(StatusBean.class);
		Input input=null;
		List statusBeans=new ArrayList();
		try {
			RandomAccessFile raf = new RandomAccessFile("statuses1.out", "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());
				statusBeans.add(statusBean);
			}
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (KryoException e) {
			System.out.println("ok");
		}finally {
			if (input != null) {
				input.close();
			}
		}
	}
发现每次这样执行都会进入KryoException中去,很是郁闷,google后,有一个新的想法,就是直接序列化list,代码如下:

public static void writeSerializeObjectToFileBykryo(String pathName)
throws IOException {
    Kryo kryo = new Kryo();
    Output output = null;
    try {
        RandomAccessFile raf = new RandomAccessFile(pathName, "rw");
        output = new Output(new FileOutputStream(raf.getFD()), 65536);// BUFFERSIZE->65536
        kryo.writeObject(output, statuses);
    } finally {
        if (output != null) {
            output.close();
        }
        statuses.clear();
    }
}

反序列化代码如下,不再报异常:

                        RandomAccessFile raf = new RandomAccessFile("statuses1.out", "r");
			input = new Input(new FileInputStream(raf.getFD()), 65536);//BUFFERSIZE->65536
			statusBeans=(List)kryo.readObject(input, ArrayList.class);
问题终于得到解决,但是上面的疑问还是没有想通,google了好久也没有找到好的解释,还请大神指教啊!


你可能感兴趣的:(eclipse,java相关,程序调试相关)