这个问题在这里已有答案:
所以,我有一个文本文件,其中包含“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
作为输出,因为跳过了替换字符。