JAVA 中的 FileReader 方法 read() 和 read(char[])

FileReader methods read() and read(char[]) in JAVA

我正在使用 read()read(char[] ch) 方法从具有 FileReader 对象的文件中读取所有字符。但是当我尝试同时使用这两种方法时,我只得到其中一种的输出。

这是我的代码片段:

class FR
{
    void filereader() throws Exception
    {
        File f = new File("abc.txt");
        FileReader fr = new FileReader(f);
        char[] ch = new char[(int)f.length()];
        fr.read(ch);
        for (char ch1 : ch)
        {
            System.out.print(ch1);
        }
        System.out.println("\n*********************************");
        int i = fr.read();
        while(i != -1)
        {
            System.out.print((char)i);
            i = fr.read();
        }
        fr.close();
    }
}

有人可以解释为什么 while 部分没有执行吗?

当你执行:

char[] ch = new char[(int)f.length()];
fr.read(ch);

您正在有效阅读整个文件
之后每次调用 read 都会 return -1 因为它是文件的末尾:

Returns the number of characters read, or -1 if the end of the stream has been reached

您可以查看 input/output here.

的用法示例

如果您想逐字或逐行阅读文件,您可能需要查看 Scanner

您的 fr.read(ch) 调用正在读取整个文件。
在此之后调用 fr.read() 将检测到 EOF 而不是 return 任何字符。

更改代码阅读部分的顺序时,您会看到不同的行为。

您还应该检查 fr.read(ch) 调用读取的字符数。这应该给出了这方面的线索。