Java 序列化/反序列化是否正确?
由于某种原因,当我反序列化我的quotes ArrayList时,我没有得到正确的对象。我想确保每当我读/写我的对象时,它总是同一个对象 序列化代码:Java 序列化/反序列化是否正确?,java,android,serialization,arraylist,Java,Android,Serialization,Arraylist,由于某种原因,当我反序列化我的quotes ArrayList时,我没有得到正确的对象。我想确保每当我读/写我的对象时,它总是同一个对象 序列化代码: private void serializeQuotes(){ FileOutputStream fos; try { fos = openFileOutput(Constants.FILENAME, Context.MODE_PRIVATE); ObjectOutp
private void serializeQuotes(){
FileOutputStream fos;
try {
fos = openFileOutput(Constants.FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(quotes);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void deserializeQuotes(){
try{
FileInputStream fis = openFileInput(Constants.FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
quotes = (ArrayList<Quote>) ois.readObject();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
为什么不在写入对象之前删除“serializeQuotes()”中的文件。这样你就可以确定,那里只有一个物体
private void serializeQuotes(){
FileOutputStream fos;
File file = new File(Constants.FILENAME);
if (file.exists()) file.delete();
try {
fos = openFileOutput(file, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(quotes);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
或者,如果您不想每次都删除文件,请在从中读取OBEJCT时使用某种迭代。输入流已关闭。抢手货问题仍然存在,因为在编写/序列化“quotes”时,我看不到它的数据类型。它应该是严格的ArrayListos.writeObject(引号)//quotes是一个已初始化的ArrayList…如果不是正确的对象,您会得到什么?同一类型的空对象,
null
或异常?我得到了以前的ArrayList。多个类正在写入此文件。我想这是一篇老文章?
private void serializeQuotes(){
FileOutputStream fos;
File file = new File(Constants.FILENAME);
if (file.exists()) file.delete();
try {
fos = openFileOutput(file, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(quotes);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}