gpt4 book ai didi

java - 我应该使用哪种 EOF 检查方法?

转载 作者:行者123 更新时间:2023-12-01 18:00:18 24 4
gpt4 key购买 nike

我目前正在准备 OCP 考试,发现这个反序列化对象列表的片段:

public static List<Animal> getAnimals(File dataFile) throws IOException,
ClassNotFoundException {
List<Animal> animals = new ArrayList<Animal>();
try (ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(dataFile)))) {
while (true) {
Object object = in.readObject();
if (object instanceof Animal)
animals.add((Animal) object);
}
} catch (EOFException e) {
// File end reached
}
return animals;
}

但是我认为 while(true) 和吞没的异常是丑陋的代码。我可以使用 in.available > 0 作为 while 条件吗?

因为 JavaDoc 说:

Returns the number of bytes that can be read without blocking.

我不确定这是否会产生任何副作用?

最佳答案

检查 available() 的问题是可能没有可用数据,但您仍然没有到达流的末尾。例如,您可能正在通过网络连接读取数据,但该连接恰好在发送数据的过程中停止了。你不在 EOF;下一个数据字节还没有到达。

<小时/>

虽然我不喜欢使用异常来检测正常情况下所期望的事情(例如到达流的末尾),EOFException 的 Javadoc表示这就是您检测流结束的方式:

Signals that an end of file or end of stream has been reached unexpectedly during input.

This exception is mainly used by data input streams to signal end of stream. Note that many other input operations return a special value on end of stream rather than throwing an exception.

但是 ObjectInputStream.readObject() 不是返回特殊值的操作之一。

所以,管住你的 Nose ,捕获这个异常。

关于java - 我应该使用哪种 EOF 检查方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41495045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com