首页 > 解决方案 > 我可以从文件中读取对象,就像它是一个数组一样吗?

问题描述

我有一个文件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();

关于如何实现这一目标而不必每次都迭代整个文件的任何建议?希望这很清楚。

标签: javafile

解决方案


在java中,数组是一个对象。你不能存储一个数组然后使用:

Example[] exampleArray = (Example[]) exampleStream.readObject();

接着

exampleArray[index]


推荐阅读