为什么FileInputStream中的read()返回一个整数? [英] Why does the read() in FileInputStream return an integer?
问题描述
这个页面显示说它是这样的当想要指示没有更多字节要读取时,方法可以返回-1。
This page shows says that it is so that the method can return -1 when it wants to indicate that there are no more bytes to be read.
但是一个字节的范围是-128到127,对吧?因为返回一个字节,read()的返回类型是不是更有意义?
But a byte ranges from -128 to 127, right? And wouldn't it make more sense for the return type of read() to be byte since it returns a byte?
感谢您的时间。
推荐答案
它将值作为 int
返回的原因是它需要返回介于0到255之间的值,以及能够指示何时没有更多字节要从文件中读取。通过使用 int
,您可以返回整个范围的正无符号值0-255,并指示文件何时完成。它不能仅提供这个 byte
值的256个不同值,其中一半是Java默认值为负值。
The reason for it returning the value as an int
is that it needs to return a value between 0-255, as well as being able to indicate when there is no more bytes to read from the file. By using an int
, you can return the full range of positive unsigned values 0-255, as well as indicate when the file is complete. It wouldn't be able to provide this with only the 256 distinct values of a byte
value, half of which are negative by Java default.
这篇关于为什么FileInputStream中的read()返回一个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!