【问题标题】:Unexpected EOF exception意外的 EOF 异常
【发布时间】:2017-10-29 17:36:31
【问题描述】:

我正在尝试将自定义(可序列化)对象的 ArrayList 读/写到文件中。它按预期工作,除了一件事:我在读取文件时收到 EOFexception。这是我的代码:

class FileHandler {
    private final String FILENAME = "storage.txt";

    ArrayList<Plane> readFromFile(Context context) {
        ArrayList<Plane> returnList = new ArrayList<>();
        Plane temp;

        try {
            FileInputStream fileInputStream = context.openFileInput(FILENAME);
            ObjectInputStream objectInStream = new ObjectInputStream(fileInputStream);


            while ((temp = (Plane)objectInStream.readObject()) != null) {
                returnList.add(temp);
            }

            objectInStream.close();
        }
        catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return returnList;
    }

    void writeToFile(ArrayList<Plane> inData, Context context) {
        FileOutputStream fileOutputStream;
        ObjectOutputStream outputStream;

        try {
            fileOutputStream = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
            outputStream = new ObjectOutputStream(fileOutputStream);

            for (Plane p: inData) {
                outputStream.writeObject(p);
            }

            outputStream.close();
            fileOutputStream.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

文件按预期写入和读取,但读取文件时出现 EOF 异常。不知道为什么。我认为我的 while 循环会确保不会发生这种情况?

  1. 为什么会出现此异常?
  2. 平面是可序列化的。如果我将 Plane 改为 parcable,是否可以读取和写入文件? (如何?)

【问题讨论】:

    标签: java android


    【解决方案1】:

    任何超出相应 writeObject 方法写入的自定义数据边界的对象数据的读取尝试都将导致抛出 OptionalDataException,并且 eof 字段值为 true。超出分配数据结尾的非对象读取将反映数据的结尾,就像它们指示流的结尾一样:按字节读取将返回 -1 作为字节读取或读取的字节数,以及原始读取将抛出 EOFExceptions。如果没有对应的 writeObject 方法,则默认序列化数据的结束标记分配数据的结束。

    这是我在https://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html找到的

    最后一次读取数据的尝试发生在没有数据时。 while-loop 条件并不真正检查是否有数据要读取。无论如何它都会尝试读取它。

    【讨论】:

    猜你喜欢
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多