我使用以下方法将ArrayLists保存到序列化对象。文件正在成功生成。但是,当我尝试阅读它时,我得到了
java.lang.ClassCastException。排队
Item item = (Item)ois.readObject();
加载文件的正确方法是什么?
保存
String storage_path = Environment.getExternalStorageDirectory() + "/notesBackup.memo";
Log.d("storage path",storage_path);
File file2 = new File(storage_path);
ArrayList<Item> items = new ArrayList();
File filesdir = getFilesDir();
ArrayList<String> itemsfiles = new ArrayList();
for (String file : filesdir.list()) {
if (file.endsWith(FILE_EXTENSION)) {
itemsfiles.add(file);
}
}
int i = 0;
while (i < itemsfiles.size())
{
try {
FileInputStream fis = openFileInput((String) itemsfiles.get(i));
ObjectInputStream ois = new ObjectInputStream(fis);
items.add((Item) ois.readObject());
FileOutputStream fos = new FileOutputStream(file2);
ObjectOutputStream ous = new ObjectOutputStream(fos);
ous.writeObject(items);
fis.close();
ois.close();
fos.close();
ous.close();
Log.d("file is creating",String.valueOf(i));
i++;
} catch (IOException e2) {
e = e2;
} catch (ClassNotFoundException e3) {
e = e3;
}
}
负载
public static ArrayList<Item> getbackupitems(Context context) {
Exception e;
ArrayList<Item> items = new ArrayList();
File filesdir = new File(Environment.getExternalStorageDirectory()+"/notesBackup.memo");
if(filesdir.exists()){
Log.d("file","found");
}
else {
Log.d("file", "not found");
}
try {
FileInputStream fis = new FileInputStream(filesdir);
ObjectInputStream ois = new ObjectInputStream(fis);
Item item = (Item)ois.readObject();
items.add(item);
fis.close();
ois.close();
Log.d(items.toString(),"");
} catch (IOException e2) {
e = e2;
} catch (ClassNotFoundException e3) {
e = e3;
}
return items;
}
答案 0 :(得分:1)
您正在阅读该列表并尝试将其投放到Item
,这就是错误的原因。
请尝试以下操作并检查
List<Item> itemList = new ArrayList<>();
itemList = (List<Item>) ois.readObject();