文件阅读器只读取文件的偶数行

Shr*_*ing 1 java filestream

public static void main(String[] args) {
    // TODO Auto-generated method stub

    BufferedReader br1 = null;
    try {
        br1= new BufferedReader(new FileReader(new File("D:\\Users\\qding\\Desktop\\spy.log")));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String str1;
    try {
        while((str1 = br1.readLine()) != null){
            str1 = br1.readLine();
            System.out.println(str1);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally{
        try {
            br1.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

文件内容有九行,但结果只显示偶数行内容,最后一行显示为空.那么为什么这个方法只读取文件的偶数行?这么奇怪....

San*_*rma 8

这是因为您正在调用readLine方法两次,并且每次调用都从底层源读取一个新行(如果它当然存在).这里的解决方案只是使用循环中的str1变量while而不是readLine第二次调用.


How*_*ard 7

在你的代码中

while((str1 = br1.readLine()) != null){   // <= 1
    str1 = br1.readLine();                // <= 2
    System.out.println(str1);
}
Run Code Online (Sandbox Code Playgroud)

您正在一次循环迭代中读取一行两次.删除第2行,它将工作.