gpt4 book ai didi

java - 为什么read()方法在EOF处返回-1?

转载 作者:行者123 更新时间:2023-12-01 21:09:09 24 4
gpt4 key购买 nike

我正在学习java.io。在read()方法文档中,我看到了定义:

read () method returns the ASCII code of input bytes (0-255) and returns -1 at the end of file

而且据我所知,EOF的ASCII码是26

那么,为什么 read() 方法对于 EOF 返回 -1 而不是 26 呢?还有,返回值-1是什么意思?

还有一个问题:空字符(即NUL),ASCII码:0,有什么用?如果文件为空(即没有数据),NUL 字符是否存在?

最佳答案

I saw the definition: "read () method returns the ASCII code of input bytes (0-255) and returns -1 at the end of file"

这个定义是不正确的。 read() 方法不返回 ASCII。它返回字节,并且不对它们进行任何解释。对于二进制文件来说,它们绝对不是 ASCII 代码。

这是 InputStream.read()真实定义...如 javadoc 中所定义。 :

"public abstract int read() throws IOException

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

请注意,没有提及 ASCII。

<小时/>

Moreover, as I known, the ASCII code of EOF is 26.

实际上,没有表示 EOF 的 ASCII 字符。代码 26 (CTRL-Z) 是 ASCII SUB 字符。它在键盘输入中用于表示 Windows 上的 EOF,但在其他上下文中则不然。事实上,在 Mac OS 和 Linux 上,ASCII 代码 4 (CTRL-D) 就可以实现这一目的。

无论如何,从 0 到 255 的所有无符号字节值都是可能出现在文件中的有效数据值。因此有必要使用不同的值来表示 EOF。

<小时/>

One more question: the null character (NUL), ASCII code: 0, is used for what?

各种各样的事情。事实上,应用程序选择将其用于任何用途。

And if the file is blank (no data), the NUL character exists or not?

NUL 字符不代表空文件或文件结尾。

如果文件没有数据,则其长度为零。文件长度是文件元数据的一部分,就像文件名、所有者和组、权限、创建时间戳等一样。

关于java - 为什么read()方法在EOF处返回-1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41560812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com