我正在保存和加载混合数据类型。我要么保存部分错误,要么加载部分错误。我正在使用缓冲串行保存和加载方法。变量lastFetchDate被定义为一个字符串,并初始化为"00/00/00"。保存数据后重新加载数据时会引发错误。怎么了?我本以为与 writeBytes 相反的是字符串的 readBytes。
保存如下:
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
您已将字符串写为 byte[],因此需要读取为 byte[]
byte [] bString = new byte[lastFetchDate.length()*2];
ois.readFully(bString, 0, bString.length);
或者,如果您使用 writeObject 方法编写为对象,则可以读取为对象,
oos.writeObject(lastFetchDate);