java - 字节如何存储在整数中

标签 java inputstream

在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.

不存在内存分配问题。 byteint 类型是原始类型。

关于java - 字节如何存储在整数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9747261/

相关文章:

java - mongodb套接字中的java.lang.Throwable错误是什么意思?

java - zip 文件与 jackrabbit

java filewriter写入实例的不完整数据

android - 无法使用 ContentResolver.openInputStream(Uri) 读取文件

java - 关于反转单链表的递归实现问题

java - 什么是出境饱和情况?在netty中如何处理?

java - 使用 Eclipse 将具有外部依赖项的 Java 项目导出到 jar

java - Eclipse 工作区加载失败,找不到项目

java - 如果我将 InputStream 的对象保存到内存中,是否意味着我将整个文件存储到内存中?

java - 使用java就地修改文件内容