Java:为什么FileReader方法.read()需要一个变量?

Java:为什么FileReader方法.read()需要一个变量?,java,filereader,Java,Filereader,因此,我有一个文本文件,其中正好包含“aaaa”和2个代码: import java.io.*; public class ex7 { public static void main(String[] args) { File file = new File("C:\\a.txt"); try { FileReader reader = new FileReader(file); int ch;

因此,我有一个文本文件,其中正好包含“aaaa”和2个代码:

import java.io.*;
public class ex7 {
    public static void main(String[] args) {
        File file = new File("C:\\a.txt");

        try {
            FileReader reader = new FileReader(file);
            int ch;
            while ((ch = reader.read()) != -1)
                System.out.print((char)ch);
            reader.close();
        }catch (Exception e) {

        }
    }
}
这个输出应该是“aaaa”

import java.io.*;
public class ex7 {
    public static void main(String[] args) {
        File file = new File("C:\\a.txt");

        try {
            FileReader reader = new FileReader(file);
            while (reader.read() != -1)
                System.out.print((char)reader.read());
            reader.close();
        }catch (Exception e) {

        }
    }
}
虽然我只更改了int变量ch的存在性,但此输出的内容为“aa”。为什么会这样?提前谢谢

reader.read()
=>每次调用字符时都读取它。所以在第二种情况下,它被称为4次,但只打印了两次

为了更好地理解,请将文件内容替换为
abab
,然后您将看到
bb
作为输出,因为会跳过备用字符。

因为您在
中调用read()一次,而(reader.read()!=-1)
忽略它返回的内容,然后再次调用它,从而读取下一个字符,in
System.out.print((char)reader.read())