为什么输入与“-1”相比?

Why is an input compared with "-1"?

我在 I/O 上复习示例代码时看到一些让我感到困惑的东西:

public class CopyBytes {
public static void main(String[] args) throws IOException {

    FileInputStream in = null;
    FileOutputStream out = null;

    try {
        in = new FileInputStream("xanadu.txt");
        out = new FileOutputStream("outagain.txt");
        int c;

        while ((c = in.read()) != -1) {
            out.write(c);
        }

如何将一个 int 值 (c) 分配给输入流 (in.read()) 中的一个字节数据?为什么while循环等待它不等于-1?

这个 (c = in.read()) 将 return -1 当输入结束时 while 循环将停止。

阅读这篇很棒的文章 answer

来自 Oracle 文档:

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. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown. A subclass must provide an implementation of this method.

Returns: the next byte of data, or -1 if the end of the stream is reached. Throws: IOException - if an I/O error occurs.

来自 FileInputStream.read() 的文档:

public int read() throws IOException

因此 read() returns 是整数,而不是字节,因此可以将其分配给 int 变量。 请注意,int 可以隐式转换为 int 而不会丢失。同样来自文档:

Returns: the next byte of data, or -1 if the end of the file is reached.

针对-1 的循环检查确定是否已到达文件末尾,如果是则停止循环。