`FileInputStream` 超过 EOF - 为什么它会产生奇怪的行为而不是抛出异常?

`FileInputStream` going past EOF - why does it produce weird behavior instead of throwing an exception?

我编写了一个程序并故意引入了一个错误,使 FileInputStream 对象读取了 EOF 字符。但是,这似乎并没有使它抛出任何异常。

这是文本文件 xanadu.txt 和产生奇怪行为的程序。

In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.

import java.io.*;

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");

            while (true) {
                int ch = in.read();
                out.write(ch);
                System.out.print((char)ch);
            }
        }
        finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }
}

in.read() 没有记录在到达 EOF 时抛出异常。它returns-1。所以你会在无限循环中不断地写-1。它的行为与记录的一样。

文档:InputStream.read()