【发布时间】:2016-07-30 20:43:57
【问题描述】:
我正在尝试使用从位置“i”开始的文件中读取“n”个字节(序列化对象)。下面是我的代码sn-p,
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,我可以看到输出。已经问过很多这样的问题,但我想知道为什么当我在特定位置写一个对象并读回它时它不起作用。可能是我做错了什么,请分享您的想法。
【问题讨论】:
-
“可能是我做错了什么”——很有可能。您是否在十六进制编辑器中检查了该文件以查看您实际编写的内容?
-
域新手。感谢十六进制编辑器..下载。
-
这不是一个好主意。您序列化的每个对象都将附加一个序列化流标头,以及涉及的每个类的数据。您的文件将比您想象的要大得多。序列化本质上是串行的,而不是随机访问。
标签: java serialization io deserialization randomaccessfile