how-to

File & Directory

How to read text file with Scanner class

java.util.Scanner class could be used for reading text file, in this example reading by rows.

We have this text file:

line 1   xxx
line 2   aaa
line 3   bbb

For reading by rows use this code:

Scanner s = null;
    
try {
  s = new Scanner( new File( "c:\\scanner.txt" ) );

  /* -- go throught lines */
        
  while ( s.hasNextLine() ) {
    System.out.println( s.nextLine() );
  }
      
}    
catch (FileNotFoundException ex) {
  Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
  if ( s != null ) { 
    s.close(); 
  } 
}
The output will be:
line 1   xxx
line 2   aaa
line 3   bbb