ObjectInputStream available()方法无法按预期工作(Java) [英] ObjectInputStream available() method doesn't work as expected (Java)

查看:482
本文介绍了ObjectInputStream available()方法无法按预期工作(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图弄清楚为什么我编写的从文件中读取对象的方法不起作用,并意识到ObjectInputStream的available()方法给出了0,即使文件没有完全读取。
在我使用FileInputStream available()方法来确定EOF并且它工作之后,该方法确实有效!

I've been trying to figure out why a method I've written to read objects from a file didn't work and realized that the available() method of ObjectInputStream gave 0 even though the file wasn't fully read. The method did work after I've used the FileInputStream available() method instead to determine the EOF and it worked!

为什么方法不起作用对于ObjectInputStram,它适用于FileInputStream吗?

Why doesn't the method work for ObjectInputStram while it works for FileInputStream?

这是代码:

public static void getArrFromFile() throws IOException, ClassNotFoundException {
    Product p;
    FileInputStream in= new FileInputStream(fName);
    ObjectInputStream input= new ObjectInputStream(in);
    while(in.available()>0){
        p=(Product)input.readObject();
        if (p.getPrice()>3000)
            System.out.println(p);
    }
    input.close();

PS-
我读过我应该使用EOF异常代替可用( )为此,但我只是想知道为什么这不起作用。

P.S- I've read that I should use the EOF exception instead of available() for this, but I just wanna know why this doesn't work.

非常感谢!!!

推荐答案

因为,正如javadoc所说, available()返回可以读取的字节数估计值没有阻止。基本InputStream实现始终返回0,因为这是一个有效的估计。但无论它返回什么,它返回0的事实并不意味着没有任何东西可以阅读。只有流不能保证至少有一个字节可以不被阻塞地读取。

Because, as the javadoc tells, available() returns an estimation of the number of bytes that can be read without blocking. The base InputStream implementation always returns 0, because this is a valid estimation. But whatever it returns, the fact that it returns 0 doesn't mean that there is nothing to read anymore. Only that the stream can't guarantee that at least one byte can be read without blocking.

这篇关于ObjectInputStream available()方法无法按预期工作(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆