为什么在 EOF 处读取 () 方法 returns -1?

why read () method returns -1 at EOF?

我正在学习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() 方法 return -1 而不是 26 用于 EOF。而且,return 值 -1 是什么意思?

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

从文件(在 "modern file" 系统上)读取的 byte 值的有效范围是 8 位(也就是说,它不是 必须的 ascii 编码,它可能是二进制的)。由于可能会返回从 0255 的任何值,因此有必要以某种方式指示文件结尾。在处理小文件时,您可能更喜欢 类 和 java.nio (generally) and the read methods available in Files 提供的方法(特别是)。

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

该定义不正确。 read() 方法不会 return ASCII。它 returns 个字节,并且 不对它们进行解释 。对于二进制文件,它们肯定不是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 字符不代表空文件或文件结尾。

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