java 关于反序列化报header错误解决方案

来源:互联网 发布:网络文体传统文体辩论 编辑:程序博客网 时间:2024/05/24 07:12

 我们在给你个文件写入一个序列化对象的时候,往往在读取得时候会报header错,这是由于我们每次序列化一个对象进去都会调用writeStreamHeader()方法,在这个方法里面有bout.writeShort(STREAM_MAGIC);  bout.writeShort(STREAM_VERSION);而这两正是在读取时候产生的错误的原因,通过查看内部的方法,原来是写入四个字节进去了!!

 那么对于这个问题有两种方法:

  1.自己写类来查看文件是不是为空,若为空就调用writeStreamHeader(),若不会空,那么不调用,

   2.若文件不为空的时候,在调用writeStreamHeader();方法后会多四个字节出来,那么你可以把这个四个字节删掉就行了


对方放一:

</pre><pre name="code" class="java">public class MyObjectOutputStream extends ObjectOutputStream{private static File file;protected MyFile(File file , FileOutputStream fileOutputStream) throws IOException, SecurityException {super(fileOutputStream);}public void writeStreamHeader()throws IOException{  //每次都会调用这个方法,所以重新写了这个方法if(file.length()==0){  //如果文件为空的时候,需要写入header否则的话不需要super.writeStreamHeader();}else{super.reset();}}public static MyObjectOutputStream newObjectOutputStream(File file , FileOutputStream fileOutputStream) throws SecurityException, IOException{MyFile.file = file;return new MyObjectOutputStream (file ,  fileOutputStream);  //创建并返回自己写的文件流,这里的参数File 必须得有}}
 
方法二: 

 fielPos=fo.getChannel().position()-4; //获取当前文件倒数的第四的下表  filePos.getChannel().truncate(pos);  //截取倒数四个字节之前的字节 os.writeObject(object); //写入文件





1 0
原创粉丝点击