我正在尝试从位置'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 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开始,我能够看到输出。已经问过很多这样的问题,但我想知道为什么当我在特定位置写一个对象并将其读回时它不起作用。可能是我做错了,请分享你的想法。
答案 0 :(得分:0)
这是你的问题:
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