Search code examples
javafileline-numbers

Read specific portion of a file by counting line number in java platform


I want to read a text file in java. I know how to read line by line from a text file by java. My question is if I have a text file that has 500 lines. I want to read the file from the 50th line to the 150th line by counting the line number first of the file. Can it be possible using LineNumberReader or any other class? I don't want to use line.equals("something") method. I am a beginner.

So far, I tried:

public class ReadLine{
    public static void main(String[] args) {
        File file = new File("H://java//newFile.txt");
        try {
            LineNumberReader linenumber = new LineNumberReader(new FileReader(file));
            linenumber.setLineNumber(50);
            String line = null;
            for (int i = linenumber.getLineNumber(); i < 151; i++) {
                System.out.println("line=" + linenumber.readLine());
            }
        } catch (Exception e) {
        }
    }
}

Solution

  • Don't call setLineNumber(). It just changes the value returned by getLineNumber(), it doesn't skip anything in the input stream. The documentation, i.e. the javadoc of LineNumberReader, says so explicitly:

    Note however, that setLineNumber(int) does not actually change the current position in the stream; it only changes the value that will be returned by getLineNumber().

    To only process some of the lines from the file, simply add an if statement:

    public static void main(String[] args) throws Exception {
        File file = new File("H://java//newFile.txt");
        try (LineNumberReader reader = new LineNumberReader(new FileReader(file))) {
            for (String line; (line = reader.readLine()) != null; ) {
                if (reader.getLineNumber() >= 50 && reader.getLineNumber() <= 150) {
                    System.out.println(reader.getLineNumber() + ": " + line);
                }
            }
        }
    }
    

    Of course, with an upper limit on line number, there is no reason to keep reading after that, so you should do it like this:

    File file = new File("H://java//newFile.txt");
    try (LineNumberReader reader = new LineNumberReader(new FileReader(file))) {
        for (String line; (line = reader.readLine()) != null; ) {
            if (reader.getLineNumber() > 150)
                break;
            if (reader.getLineNumber() >= 50) {
                System.out.println(reader.getLineNumber() + ": " + line);
            }
        }
    }
    

    If you don't need to know the line number, then with Java 8+ Streams, it's even easier:

    Path file = Paths.get("H://java//newFile.txt");
    Files.lines(file).limit(150).skip(49).forEach(System.out::println);