Reading a specific line from a text file in Java

后端 未结 9 660
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 07:34

Is there any method to read a specific line from a text file ? In the API or Apache Commons. Something like :

String readLine(File file, int lineNumber)


        
相关标签:
9条回答
  • 2020-11-27 07:54

    guava has something similar:

    List<String> Files.readLines(File file, Charset charset);
    

    So you can do

    String line = Files.readLines(file, Charsets.UTF_8).get(lineNumber);
    
    0 讨论(0)
  • 2020-11-27 07:54

    If you are going to work with the same file in the same way (looking for a text at certain line) you can index your file. Line number -> offset.

    0 讨论(0)
  • 2020-11-27 07:58

    Unfortunately, unless you can guarantee that every line in the file is the exact same length, you're going to have to read through the whole file, or at least up to the line you're after.

    The only way you can count the lines is to look for the new line characters in the file, and this means you're going to have to read each byte.

    It will be possible to optimise your code to make it neat and readable, but underneath you'll always be reading the whole file.

    If you're going to reading the same file over and over again you could parse the file and create an index storing the offsets of certain line numbers, for example the byte count of where lines 100, 200 and so on are.

    0 讨论(0)
  • 2020-11-27 07:58

    Using File Utils:

    File fileFeatures = new File(
                    "Homework1AdditionalFiles/jEdit4.3/jEdit4.3ListOfFeatureIDs.txt");
    String line = (String) FileUtils.readLines(fileFeatures).get(lineNumber);
    
    0 讨论(0)
  • 2020-11-27 08:01

    Not that I'm aware of.

    Be aware that there's no particular indexing on files as to where the line starts, so any utility method would be exactly as efficient as:

    BufferedReader r = new BufferedReader(new FileReader(file));
    for (int i = 0; i < lineNumber - 1; i++)
    {
       r.readLine();
    }
    return r.readLine();
    

    (with appropriate error-handling and resource-closing logic, of course).

    0 讨论(0)
  • 2020-11-27 08:15

    If the lines you were reading were all the same length, then a calculation might be useful.

    But in the situation when the lines are different lengths, I don't think there's an alternative to reading them one at a time until the line count is correct.

    0 讨论(0)
提交回复
热议问题