java - 我可以从文件中读取对象,就像它是一个数组一样吗?
问题描述
我有一个文件example.dat,其中存储了不同的对象,比如说“示例”类的 10 个实例。现在,在给定的时间,我需要读取一个特定的示例对象,假设我首先读取第 5 个,然后是第 3 个,然后是第 8 个等等。基本上,我想从那个文件中读取,就好像它是一个数组一样。有什么方法可以实现吗?现在我有:
public static Example loadExampleFromFile(int index){
ObjectInputStream exampleStream = null;
try{
exampleStream = new ObjectInputStream(new FileInputStream("Example.dat"));
//Now I should point in the file at the beginning of the Example object
//which is the index-th object stored into the file
return (Example) exampleStream.readObject();
关于如何实现这一目标而不必每次都迭代整个文件的任何建议?希望这很清楚。
解决方案
在java中,数组是一个对象。你不能存储一个数组然后使用:
Example[] exampleArray = (Example[]) exampleStream.readObject();
接着
exampleArray[index]
推荐阅读
- leaflet - 如何使用 Leaflet.Draw GeometryUtil 计算多边形的面积
- windows - 通过 Ansible 请求 Windows 会话 ID
- xpath - 如何从 xpath 中排除子节点?
- python - Flask 将变量从应用程序主文件传递到蓝图
- perl - 使用 LWP::UserAgent 和 HTTP::Request 通过代理检查安全连接
- c# - 如何仅选择第一个可用的复选框硒
- database - Dynamo 数据库 GSI
- php - 无法显示存储过程的数据
- sql - 从表中仅获取最新的修订记录
- ios - 我的 PWA 在 Safari 上缺少“Web Push”的解决方法