0
我想從位置'我'開始使用從文件讀'n'字節(序列化的對象)。這裏是我下面的代碼片段,RandomFileAccess - java.io.StreamCorruptedException
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,我能夠看到輸出。有很多這樣的問題已經提出,但我想知道爲什麼當我在特定位置寫入對象並將其讀回時,它不工作。可能是我做錯了什麼,請分享你的想法。
_「可能是我做錯了什麼」 _ - 很可能。你有沒有在十六進制編輯器中檢查文件,看看你實際寫了什麼? –
新的域名。感謝十六進制編輯器..下載。 – Anandan
這不是一個好主意。序列化的每個對象都會有一個序列化流標題作爲前綴,併爲每個涉及的類提供數據。你的文件將比你想象的大得多。序列化本質上是串行的,而不是隨機訪問。 – EJP