在 Android APK 2.2 及更高版本中保存和加载 Object[] 信息

发布于 2024-11-24 13:33:52 字数 769 浏览 1 评论 0原文

因此,在对这个主题进行了广泛的研究之后,我提出了以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

檐上三寸雪 2024-12-01 13:33:52

您的数组真的只包含对象还是它们实际上是用户定义的类型?如果是这样,请考虑这样一个事实:您必须仔细设计类才能使序列化发挥作用。如果您还没有这样做,我强烈建议您阅读 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文