在 Android APK 2.2 及更高版本中保存和加载 Object[] 信息
因此,在对这个主题进行了广泛的研究之后,我提出了以下代码:
private void loadInformation() throws IOException, ClassNotFoundException{
FileInputStream fis = openFileInput("save");
ObjectInputStream in= new ObjectInputStream(fis);
loadedInformation=(Object[]) in.readObject(); //loadedInformation is a Object[]
in.close();
fis.close();
}
private void saveInformation() throws IOException{
FileOutputStream fos = openFileOutput("save", Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(getAllInformation()); //getAllInformation() returns Object[]
out.close();
fos.close();
}
所有这些似乎都工作得很好,唯一的问题是稍后条件语句将在不应该通过的时候开始通过,并且经过几次保存和加载它只会崩溃。看起来不错,但如果(变量等于一!=变量等于一)结果为真,我一定是在做一些愚蠢的事情。
So after extensive research on the subject, I've come up with the following bit of code:
private void loadInformation() throws IOException, ClassNotFoundException{
FileInputStream fis = openFileInput("save");
ObjectInputStream in= new ObjectInputStream(fis);
loadedInformation=(Object[]) in.readObject(); //loadedInformation is a Object[]
in.close();
fis.close();
}
private void saveInformation() throws IOException{
FileOutputStream fos = openFileOutput("save", Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(getAllInformation()); //getAllInformation() returns Object[]
out.close();
fos.close();
}
All of which seems to work just fine, only problem is later on conditionals will begin passing when they shouldn't be and after a few saves and loads it will just crash. It seems ok but I must be doing something silly if (variable equaling one != variable equaling one) comes out true.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的数组真的只包含对象还是它们实际上是用户定义的类型?如果是这样,请考虑这样一个事实:您必须仔细设计类才能使序列化发挥作用。如果您还没有这样做,我强烈建议您阅读 Effective Java 中的“第 11 章:序列化” 。
Does your array really contain only objects or are they actually a user-defined type? If so, consider the fact that you must design your class in a careful manner for serialization to work. If you haven't done so already, I highly recommend reading "Chapter 11: Serialization" from Effective Java.