Java: 为什么 FileReader 方法 .read() 需要一个变量?
Java: why does FileReader method .read() needs a variable?
所以,我有一个文本文件,其中正好包含 "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
作为输出,因为备用字符被跳过。
所以,我有一个文本文件,其中正好包含 "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
作为输出,因为备用字符被跳过。