Using a scanner for a multi-line text file

I am working on a program that reads a text file. I have to execute a separate method for each line of the file. I could do something like this:

LineNumberReader myReader = new LineNumberReader(new FileReader("filename"));

Scanner scanner = new Scanner(myReader.readLine());
while (scanner.hasNext()) { ... }

And put the last two lines in a loop so that I can parse the tokens for each line. But I was wondering if there is a way to do this without instantiating a new scanner object at each iteration.

+4
source share
3 answers

Java code to read each line with one scanner:

Scanner myScanner = new Scanner(new File("filename"));
while (myScanner.hasNextLine())
{
   String line = myScanner.nextLine();
    ...
}
+2
source

You can combine the reader and scanner, just pass the reader to the scanner, and then cycle

LineNumberReader myReader = new LineNumberReader(new FileReader("filename"));

Scanner myScanner = new Scanner(myReader);  // <== scanner uses Reader
while (myScanner.hasNextLine()) {
    String line = myScanner.nextLine();
}
+1
source

@Max Zoome - , : infinite. :

String line;
while (myScanner.hasNextLine() && (line=myScanner.nextLine()!=null))
{
   // Do whatever you want to do 
}

line by line, BufferedReader, ,

Since it is Scannerused to parse tokens from the contents of the stream, as well as BufferedReader- synchronized, but Scanner- no.

FileReader in = new FileReader("yourFileName");
BufferedReader br = new BufferedReader(in);

while ((line=br.readLine()) != null) {
    System.out.println(line);
}
in.close();
0
source

All Articles