随机文件访问 - java.io.StreamCorruptedException

RandomFileAccess - java.io.StreamCorruptedException

我正在尝试使用从位置 'i' 开始的文件读取 'n' 字节(序列化对象)。下面是我的代码片段,

public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchAlgorithmException {
      String s = "XYZ";
      RandomAccessFile f = new RandomAccessFile("/home/Test.txt", "rw");
      f.write(s.getBytes());
      FingerPrint finger = new FingerPrint("ABCDEFG", "ABCD.com");
      Serializer ser = new Serializer();
      byte[] key = ser.serialize(finger);//Serializing the object
      f.seek(3);
      f.write(key);
      byte[] new1 = new byte[(int)f.length()-3];
      int i=0;
      for(i=3;f.read()!=-1;i++){
        f.seek(i);
        new1[i]=f.readByte();
      }
      FingerPrint finger2 = (FingerPrint) ser.deserialize(new1);//deserializing it
      System.out.println("After reading:"+finger2.getURL());
}

我遇到以下异常,

 Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 00000000
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:807)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:302)

这是我的序列化器 class,

class Serializer {

public static byte[] serialize(Object obj) throws IOException {
    try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
        try(ObjectOutputStream o = new ObjectOutputStream(b)){
            o.writeObject(obj);
        }
        return b.toByteArray();
    }
}

public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
    try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
        try(ObjectInputStream o = new ObjectInputStream(b)){
            return o.readObject();
        }
    }
}

}

如果我不向文件写入任何字符串,只读取对象,即从 0 开始到 eof,我就能看到输出。已经问了很多这样的问题,但我想知道为什么当我在特定位置写一个对象并读回它时它不起作用。可能是我做错了什么,请分享你的想法。

这是您的问题:

  f.seek(3);
  f.write(key);
  byte[] new1 = new byte[(int)f.length()-3];
  int i=0;
  for(i=3;f.read()!=-1;i++){
          ^^^^^^^^

此时文件指针位于 EOF,因为您刚刚写入了序列化字节并且还没有移动文件指针。这个循环是不必要的,你应该 seek(3) 然后直接读入 new1 就像

byte[] new1 = new byte[(int) f.length() - 3];
f.seek(3);
f.read(new1);
FingerPrint finger2 = (FingerPrint) ser.deserialize(new1);// deserializing