Using BufferedReader to read Text File

前端 未结 9 1520
你的背包
你的背包 2020-11-29 04:29

I\'m having problems with using the BufferedReader

I want to print the 6 lines of a text file:

public class Reader {

public static void main(String[         


        
9条回答
  •  旧时难觅i
    2020-11-29 04:59

    This is the problem:

    while (br.readLine() != null) {
        System.out.println(br.readLine());
    }
    

    You've got two calls to readLine - the first only checks that there's a line (but reads it and throws it away) and the second reads the next line. You want:

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    

    Now we're only calling readLine() once per loop iteration, and using the line that we've read both for the "have we finished?" and "print out the line" parts.

提交回复
热议问题