2012-06-28 26 views
0

我正在保存並加載混合數據類型。我要麼保存部分錯誤,要麼裝載部分錯誤。我正在使用緩衝串行保存和加載方法。 變量lastFetchDate被定義爲一個字符串並初始化爲「00/00/00」。 保存後重新加載數據時會引發錯誤。哪裏不對?我會認爲與writeBytes相反的是字符串readBytes。保存字符串序列化並緩存android JAVA.IO ObjectInputStream

保存如下:

FileOutputStream fos = new FileOutputStream("userPrefs.dat"); 
    BufferedOutputStream bos = new BufferedOutputStream(fos); 
    ObjectOutputStream oos = new ObjectOutputStream(bos); 
    oos.writeBytes(lastFetchDate); 
    // I close all streams 

加載如下:

FileInputStream fis = new FileInputStream("userPrefs.dat"); 
    BufferedInputStream bis = new BufferedInputStream(fis); 
    ObjectInputStream ois = new ObjectInputStream(bis); 
    lastFetchDate=(String)ois.readObject(); //<<<<< Error thrown here 
    // I close all streams 
+0

你已經寫了字符串爲byte []所以需要讀爲byte [],你將不得不使用http://developer.android.com/reference/java/io/ObjectInputStream.html#readFully(byte [ ],int,int) –

回答

1

你已經寫字符串作爲字節[]所以需要閱讀作爲字節[]

byte [] bString = new byte[lastFetchDate.length()*2]; 
    ois.readFully(bString, 0, bString.length); 

或者如果你使用writeObject method寫成Object,那麼你可以讀爲對象,

oos.writeObject(lastFetchDate); 
+0

作爲一個對象工作的寫作和閱讀。謝謝。 – user1445716