Make BufferedReader start from the middle of a .txt file rather than the beginning?

前端 未结 3 1729
清歌不尽
清歌不尽 2021-01-18 04:16

I have a LONG .txt file that contains almost 6000 lines! Sometimes I need to retrieve the info. in line 5000. Is it possible to start reading from line 5000 rather than sta

相关标签:
3条回答
  • 2021-01-18 04:38

    Whether 6000 lines are long or not depends on the average line length. Even with 100 characters per line, this is not really long.

    Nevertheless, you can read from line 5000 if you know where line 5000 starts. Unfortunately, most of the time you'll have to read lines 1 through 4999 to find that out.

    0 讨论(0)
  • 2021-01-18 04:51

    I believe there is a skip method for the BufferedReader in java, which allows you to skip x characters. To get to a specific line is much harder though.

    Edit: Found it

    0 讨论(0)
  • 2021-01-18 04:57

    As 5000 lines is not so big, and it will do a sequential file access, this simple idea could work:

    BufferedReader in = new BufferedReader(new InputStreamReader(fileName));
    for (int i = 0; i < 5000 && in.ready; in.readLine()) { }
    if (in.ready()) {
      // you are at line 5000;
    } else {
      // the file is smaller than 5000 lines
    }
    

    Another idea is to use the bufferedRead.skip(n) method, but for it every line should have the same length. By example, each line having 100 characters, you will need to do:

    int ls = System.getProperty("line.separator").length();
    in.skip((100 + ls) * 5000);
    
    0 讨论(0)
提交回复
热议问题