1
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();
        }
    }
}

The content of file have nine lines, but the result only show the even number line content, and the last line as null. so why this method only reads the even number line of the file? So strange....

4

4 回答 4

8

This is because you are invoking readLine method twice and each invocation reads a new line from the underlying source (if it exists of course). The solution here is simply to use the str1 variable from the while loop and not invoke the readLine for the second time.

于 2012-06-16T07:17:45.160 回答
7

In your code

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

You are reading a line two times in one loop iteration. Remove line 2 and it will work.

于 2012-06-16T07:18:20.120 回答
4

Notice that you read the line twice:
once in the 'while' declaration, and once inside the loop.
Remove the 'str1 = br1.readLine();' in the first line of the 'while' loop.

于 2012-06-16T07:17:49.793 回答
3

因为你使用readLine()了两次。你应该修改它如下

str1 =  br1.readLine();
while(str1 != null){
        System.out.println(str1);
        str1 = br1.readLine();            
    }
于 2012-06-16T07:19:51.380 回答