简体   繁体   中英

Using scanner for a multi-line text file

I'm 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 latter two lines in a loop so I can parse the tokens for each line. But I was wondering if there is any way I can do this without instantiating a new scanner object every iteration.

Java code to read each line with one scanner:

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

You can combine the Reader and a Scanner, just pass the Reader into the Scanner, and then loop

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

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

@Max Zoome's example is a good approach but it has one problem that this loop will go to infinite So i suggest you to use below version:

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

Alternative Solution

When you want to read a file line by line using BufferedReader is a good approach ,

Since Scanner is used for parsing tokens from the contents of the stream as well as BufferedReader is synchronized and Scanner is not .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM