在java.io.*包的InputStream类中:
int read() 抛出 IOException
read()返回一个字节,因为它在字节流类下,但它存储在整数中,没有任何错误。
为什么会这样??以及这是怎么发生的。也帮我设计一下内存分配
最佳答案
上下文由 javadoc 给出,其中表示:
"Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned."
在底层,read
方法要么返回一个字节,要么流位于 EOF 位置。因此,返回值可以有 257 种可能的状态,并且(显然)这不适合一个字节。 API 通过返回一个 int
来处理这个问题,该整数按照我上面引用的 javadoc 摘录指定的方式进行编码。
我没有看过代码,但我希望它大概是这样的:
if (eof) {
return -1;
} else {
// Casting to an int sign extends to 32 bits,
// and we then take the bottom 8 bits.
return ((int) someByte) & 0xff;
}
当你得到结果时,你需要做这样的事情:
int res = is.read();
if (res == -1) {
// handle EOF case ...
} else {
byte b = (byte) res;
// handle the byte ...
}
<小时/>
Help me the memory allocation design also.
不存在内存分配问题。 byte
和 int
类型是原始类型。
关于java - 字节如何存储在整数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9747261/