0

I have a question about something I've done in the past, but never really thought if it was the most efficient method to use.

Let's say I have a text file, where each line contains something important and let's then say I have multiple sets of these lines, each corresponding to a unique environment...so for example:

1
String that I need to parse for specific tokens..
2
String that I need to parse for specific tokens..
String that I need to parse for specific tokens..
3
String that I need to parse for specific tokens..
String that I need to parse for specific tokens..
String that I need to parse for specific tokens..

So given the above input file, my past way of solving this would be something similar to the following (semi-pseudocode!):

BufferedReader inputFile = new BufferedReader(new FileReader("file.txt"));
while(inputFile.hasNextLine())
{    
     Scanner line = new Scanner(inputFile.nextLine());
     //parse the line looking for tokens

}

inputFile.close();

My issue with this is it seems incredibly inefficient to create a new Scanner object for every line I have in my BufferedReader.

Is there a better way to achieve this functionality?

One suggestion may be to scan the whole document by tokens, but my issue with that is I won't be able to keep track of how many strings are apart of the subset (indicated by the integer); or at least I can't think of another solution to that other than to decrement a counter every time I look at a new line.

Thanks in advance!

user2019260
  • 143
  • 4
  • 10

1 Answers1

0

check out with this;

public static void main(String[] args) throws IOException {

        BufferedReader bf = new BufferedReader(new FileReader(new File("d:/sample.txt")));
        LineNumberReader lr = new LineNumberReader(bf);
        String line = "";            
        while ((line = lr.readLine()) != null) {
            System.out.println("Line Number " + lr.getLineNumber() +
                    ": " + line);                
        }
    }
Shekhar Khairnar
  • 2,643
  • 3
  • 26
  • 44