无法使用以下 Java 代码读取完整文件
Unable to read complete file with below Java Code
读取文件时部分代码工作正常
//代码A
try{
String s1;
f = new FileReader("C:\Test.txt");
f1 = new BufferedReader(f);
while((s1 = f1.readLine())!=null)
{
System.out.println(s1);
}
}
但这个不是:
//代码B
try{
String s1;
f = new FileReader("C:\Test.txt");
f1 = new BufferedReader(f);
while((f1.readLine())!=null)
{
s1=f1.readLine();
System.out.println(s1);
}
}
我觉得代码A和B是一样的;但是代码 A 读取了文件的全部内容,而代码 B 则没有。为什么?
在代码 B 中,您在一次迭代中调用了 readLine()
两次,因此在一次迭代中读取了 2 行,最后仅每隔两行打印一次。即使您没有将 f1.readLine()
分配给任何内容,该行仍会被读取并且 reader 会继续到下一行。
读取文件时部分代码工作正常
//代码A
try{
String s1;
f = new FileReader("C:\Test.txt");
f1 = new BufferedReader(f);
while((s1 = f1.readLine())!=null)
{
System.out.println(s1);
}
}
但这个不是:
//代码B
try{
String s1;
f = new FileReader("C:\Test.txt");
f1 = new BufferedReader(f);
while((f1.readLine())!=null)
{
s1=f1.readLine();
System.out.println(s1);
}
}
我觉得代码A和B是一样的;但是代码 A 读取了文件的全部内容,而代码 B 则没有。为什么?
在代码 B 中,您在一次迭代中调用了 readLine()
两次,因此在一次迭代中读取了 2 行,最后仅每隔两行打印一次。即使您没有将 f1.readLine()
分配给任何内容,该行仍会被读取并且 reader 会继续到下一行。