所以我对序列化场景很陌生,我不知道是否可以序列化哈希表然后将其保存到文件中......但这是我迄今为止尝试过的......出于某种原因到我的代码部分而不是执行 Try 块?
public void addDataIntoFlashCardFile(Context context, Hashtable<Integer, ArrayList<Deck>> data) {
try {
FileOutputStream fos = context.openFileOutput(
FLASHCARDS_FILENAME, Context.MODE_PRIVATE
| Context.MODE_APPEND);
ObjectOutputStream osw = new ObjectOutputStream(fos);
osw.writeObject(data);
} catch (FileNotFoundException e) {
// catch errors opening file
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "calles", Toast.LENGTH_SHORT).show();
}
}
在这里,我尝试从文件中读取它(这不起作用,因为它首先不会写入文件)
try {
Hashtable<Integer, ArrayList<Deck>> temp = new Hashtable<Integer, ArrayList<Deck>>();
FileInputStream myIn = context.openFileInput(FLASHCARDS_FILENAME);
ObjectInputStream IS = new ObjectInputStream(myIn);
Toast.makeText(context, "here", Toast.LENGTH_SHORT).show();
try {
temp = (Hashtable<Integer, ArrayList<Deck>>)IS.readObject();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
IS.close();
//testing purposes
for (int i = 0; i < temp.size(); i++) {
for (int p = 0; p < temp.get(i).size(); p++) {
for (int q = 0; q < temp.get(i).get(p).getDeck().size(); q++) {
Toast.makeText(context, temp.get(i).get(p).getDeck().get(q).getQuestion(), Toast.LENGTH_LONG).show();
}
}
}
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "here", Toast.LENGTH_SHORT).show();
}
}