android/java:使用其他东西而不是ObjectInputStream来加载对象
我有一堆对象存储在几个文件中,我需要在应用程序启动时将其加载到内存中,这就是我的做法:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 协议缓冲区 或 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.
您是否尝试过将 FileInputStream 包装到 BufferedInputStream 中?它最大限度地减少了与底层流的昂贵交互。
Have you tried wrapping your FileInputStream into a BufferedInputStream? It minimizes expensive interaction with the underlying stream.