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都会返回-1,因为它是文件的末尾:

返回

读取的字符数,如果已到达流的末尾,则返回 -1

您可以在此处查看输入/输出的用法示例。

如果要逐字或逐行读取文件,则可能需要查看扫描仪。

您的fr.read(ch)调用正在读取整个文件。
在此之后调用fr.read()将检测EOF并且不返回任何字符。

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

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

最新更新