Chris
Chris

Reputation: 2284

Get current line number from bufferedReader

I have different text files I would like to read, and I am using BufferedReader for it like this:

int theMax = 0;
    int theTypes = 0;
    int []theSlices = {};
    /*
        INPUT1:
        17 4
        2 5 6 8  

        INPUT2:
        100 10
        4 14 15 18 29 32 36 82 95 95                                

    */

    try {
        FileReader reader = new FileReader("INPUT1.in");
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            String[] numbers = line.split(" ");

            System.out.println(numbers[0]);
            System.out.println(line);
        }
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    ;

My problem is that I would like to set the values for theMax, theTypes & theSlices but for that I need to get the current line number and I have no idea how to do that. Reading the file works and println(numbers[0] prints 17 and 2. I am kind of stuck here so I am happy for every help.

Example for INPUT1: theMax = 17 theTypes = 4 theSlices = 2 5 6 8

Upvotes: 3

Views: 7900

Answers (4)

14241354
14241354

Reputation: 211

Use java.io.LineNumberReader.

LineNumberReader is a subclass of BufferedReader that keeps track of line numbers. It provides a getLineNumber() method for getting the current line number.

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/LineNumberReader.html

Example:

import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

public class Example {
    public static void main(String[] args) throws IOException {
        try (FileReader fr = new FileReader("input.txt");
             LineNumberReader r = new LineNumberReader(fr)) {
            String next;
            while ((next = r.readLine()) != null) {
                System.out.println("line number " + r.getLineNumber() + " = " + next);
            }
        }
    }
}

Upvotes: 3

GabiF
GabiF

Reputation: 11

First of all, as far as I know (and having read the official Java documentation for it here - https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html), the BufferedReader class does not in itself give you a mechanism (e.g. a getCurrentLine() method) to determine the current line.

However, there is absolutely nothing stopping you from keeping track of current line number yourself through, say, a counter variable.

Therefore, the relevant section of your code would look like:

        int currentLine = 0;
        while ((line = bufferedReader.readLine()) != null) {
            currentLine++;

            String[] numbers = line.split(" ");

            /* NOTE: this can be numbers.length >= 2 if you don't care to enforce 
            having exactly 2 numbers as the first line 
            */
            if(currentLine == 1 && numbers.length == 2) {
                    theMax = Integer.valueOf(numbers[0]);
                    theTypes = Integer.valueOf(numbers[1]);
            } else {
                for(int index = 0; index < numbers.length; index++) {
                        theSlices[index] = Integer.valueOf(numbers[index]);
                }
            }
        }
        // do something with read values

I would also like to mention that your code could be improved here and there, for example:

  1. You can replace your try with a try-with-resources, such that your readers are managed/closed automatically even if an exception occurs.
  2. If you decide not to use try-with-resources, then you'll need to move your reader.close() method call in a finally block, because if an exception actually occurs you are never closing your resource.
  3. These 2 lines
        FileReader reader = ;
        BufferedReader bufferedReader = new BufferedReader(reader);

can be simplified into:

        BufferedReader bufferedReader = new BufferedReader(new FileReader("INPUT1.in"));

and then you only need to manage the bufferedReader instance if sticking to try instead of try-with-resources.

Hope this helps.

PS: not saying that my code snippet above is perfect, I'm sure it can be written more cleanly

Upvotes: 1

Brendon Randall
Brendon Randall

Reputation: 1446

Not sure I totally understand what you are after, but for just keeping track of the line numbers, create a variable that you increment in your while loop

i.e.

try {
        FileReader reader = new FileReader("INPUT1.in");
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line;
        long currentLineNr = 0;
        while ((line = bufferedReader.readLine()) != null) {
            currentLineNr++;
            String[] numbers = line.split(" ");

            System.out.println(numbers[0]);
            System.out.println(line);
            //Use the currentLineNr how you like
        }
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

Upvotes: 1

kutschkem
kutschkem

Reputation: 8163

Very simple: you keep track yourself.

    String line;
    int currentLine = 0;

    while ((line = bufferedReader.readLine()) != null) {
        String[] numbers = line.split(" ");

        System.out.println("Linenumber " + currentLine);
        System.out.println(numbers[0]);
        System.out.println(line);
        currentLine ++;
    }
    reader.close();

Upvotes: 3

Related Questions