Scanner class is mainly used for capturing and parsing text from various sources such as files,strings etc and in this tutorial we will see some of Scanner class' usages.

Parsing text from user input

One of the most classic examples on how Scanner class can be used is capturing and parsing user input.For example:

public class ScannerTest {
    
    public static void main(String args []){
        try {
            Scanner userInputTextScanner=new Scanner(System.in);
            while(userInputTextScanner .hasNext()){
                System.out.println(userInputTextScanner.next());
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ScannerTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
   
}

Parsing text from text files

Another usage of Scanner class is parsing text from files.For example:

public class ScannerTest {
    
    public static void main(String args []){
        try {
            Scanner fileTextScanner=new Scanner(new File("C:\\textFile.txt"));
            while(fileTextScanner.hasNext()){
                System.out.println(fileTextScanner.nextLine());
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ScannerTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
   
}

Parsing text from string

Since scanner classs can be used for parsing text and primitive types from strings it could be used as an alternative to splitting request parameters.For example:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException
  {
  String parameter=request.getParameter(â??someParameterâ??);
Scanner parameterScanner=new Scanner(parameter);
 while(parameterScanner .hasNext()){
                //Some cool processing goes here
            }
  }