Java中InputStream.available()的作用是什么?
InputStream.available()
在 Java 中做什么?我阅读了文档,但仍然无法理解。
医生说:
返回可以从此输入流读取(或跳过)的字节数,而不会被该输入流的方法的下一个调用者阻塞。下一个调用者可能是同一个线程或另一个线程。
类InputStream的可用方法始终返回0。
阻塞是什么意思?它只是意味着同步调用吗?
最重要的是,available() 方法的目的是什么?
What does InputStream.available()
do in Java? I read the documentation, but I still cannot make it out.
The doc says:
Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream. The next caller might be the same thread or or another thread.
The available method for class InputStream always returns 0.
What do they mean by blocking? Does it just mean a synchronized call?
And most of all, what is the purpose of the available()
method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 InputStreams 中,
read()
调用被称为“阻塞”方法调用。这意味着,如果在方法调用时没有可用数据,则该方法将等待数据可用。available()
方法告诉您可以读取多少字节,直到read()
调用将阻塞程序的执行流程。在大多数输入流上,所有对read()
的调用都是阻塞的,这就是 available 默认返回 0 的原因。但是,在某些流(例如具有内部缓冲区的 BufferedInputStream)上,某些字节会被读取并保存在内存中,因此您可以在不阻塞程序流的情况下读取它们。在这种情况下,
available()
方法会告诉您缓冲区中保存了多少字节。In InputStreams,
read()
calls are said to be "blocking" method calls. That means that if no data is available at the time of the method call, the method will wait for data to be made available.The
available()
method tells you how many bytes can be read until theread()
call will block the execution flow of your program. On most of the input streams, all call toread()
are blocking, that's why available returns 0 by default.However, on some streams (such as
BufferedInputStream
, that have an internal buffer), some bytes are read and kept in memory, so you can read them without blocking the program flow. In this case, theavailable()
method tells you how many bytes are kept in the buffer.这里的阻塞与线程或同步无关。相反,它与阻塞 IO 有关(有关详细信息,请参阅此)。如果您发出读取请求,并且通道没有可用的通道,则阻塞调用将等待(或阻塞)直到数据可用(或通道关闭,引发异常等)。
那么为什么要使用
available() ?因此您可以确定要读取多少字节,或确定是否要阻塞。
请注意,Java 也具有非阻塞 IO 功能。请参阅此处 了解更多详情
Blocking doesn't relate to threading or synchronisation here. Instead it relates to blocking IO (see this for more info). If you issue a request to read, and the channel has none available, a blocking call will wait (or block) until data is available (or the channel is closed, throws an exception etc.)
So why use
available()
? So you can determine how many bytes to read, or determine whether you're going to block.Note that Java has non-blocking IO capabilities as well. See here for more details