为什么这些构造中的输出在 java 的文件处理的 read() 函数中不同?

Why is the output in these constructs different in java's file handling's read() function?

如果 read() 被写入并在其内部赋值,而它运行良好。

while((ch=fr.read())!=-1){
            System.out.print((char)ch);
        }

Output: This is a text.

但如果它在外面使用,它会提供一种加密输出

while(fr.read()!=-1){
            ch=fr.read();
            System.out.print((char)ch);
        }

Output: hsi et?

这种行为背后的原因是什么?

read() 方法读取一个字符并将光标移动到下一个字符。

在第一个 while 循环中,您阅读了一次,但在第二个循环中,您阅读了两次。因此,如果在一个文件中,只有字符,那么第一个循环将打印该字符,而第二个循环将在条件块中的第一个语句之后到达文件末尾,因此行 ch=fr.read(); 将 return -1。