android/java:使用其他东西而不是ObjectInputStream来加载对象

发布于 2024-11-07 19:41:25 字数 510 浏览 0 评论 0原文

我有一堆对象存储在几个文件中,我需要在应用程序启动时将其加载到内存中,这就是我的做法:

    FileInputStream fis = null;
    ObjectInputStream ois = null;
    Object result = null;
    try {
        fis = new FileInputStream(inFile);
        ois = new ObjectInputStream(fis);
        result = ois.readObject();
        //and then do something with result

问题是,当我尝试加载对象时(HashMap) 的大小超过 500k,在我的手机上需要很长时间。我不确定这是否是 ObjectInputStream 的问题,如果是,是否还有其他更快的方法来存储和从文件中检索对象?越快越好,非常感谢。

I have a bunch of objects stored in several files that I need to load into memory at the start of my app, this is how I do it:

    FileInputStream fis = null;
    ObjectInputStream ois = null;
    Object result = null;
    try {
        fis = new FileInputStream(inFile);
        ois = new ObjectInputStream(fis);
        result = ois.readObject();
        //and then do something with result

The problem is, when I try to load an object(HashMap<Integer, int[]>) of size more than 500k, it takes forever on my phone. I am not sure if it is the problem of ObjectInputStream, if it is, are there any other faster ways to store and retrieve objects from a file? The faster the better, Thanks a lot.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

奈何桥上唱咆哮 2024-11-14 19:41:25

您可以使用 协议缓冲区 或 Android 的本机序列化:包裹

更新:

为什么要在一个文件中存储这么多对象并同时将它们全部加载到内存中?正如您发现的那样,这需要很长时间并且使用大量内存。您需要这个有什么特殊原因吗?

您应该使用数据库 - 它允许您有选择地查询数据并仅加载特定时间所需的对象。

You could use Protocol Buffers or Android's native serialization: Parcel.

update:

Why are you storing so many objects in a file and loading them all at the same time into memory? As you found out it takes forever and uses a lot of memory. Is there any particular reason you need this?

You should be using a database - it lets you selectivelly query data and only load objects that you need at particular time.

可爱咩 2024-11-14 19:41:25

您是否尝试过将 FileInputStream 包装到 BufferedInputStream 中?它最大限度地减少了与底层流的昂贵交互。

...
ois = new ObjectInputStream(new BufferedInputStream(fis));
...

Have you tried wrapping your FileInputStream into a BufferedInputStream? It minimizes expensive interaction with the underlying stream.

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