java.util.Scanner nextLine()

Description :

This java tutorial shows how to use the nextLine() method of Scanner class of java.util package. This method returns a String which corresponds to the skipped line of the Scanner object.

Method Syntax :

public String nextLine()

Parameter Input :

 

DataType Parameter Description
N/A N/A N/A

 

Method Returns :

This method simply returns the string the current line.

Compatibility Version :

Requires Java 1.5 and up

Exception :

NoSuchElementException

– The NoSuchElementException is thrown if and only if there is no available token

IllegalStateException

– This exception is thrown if the scanner is already closed before invoking the nextLine() method.

Discussion :

The Scanner nextLine() method returns the line skipped during method invocation and the Scanner object moves in to the succeeding line. This method alongside with hasNextLine() method of Scanner is helpful in reading a file line by line.

Java Code Example :

This java example source code demonstrates the use of nextLine() method of Scanner class. Basically this example source makes use of hasNextLine() and nextLine() method of Scanner class to iterate through the contents of a file line by line.

package com.javatutorialhq.java.tutorial.scanner;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/*
 * Example java source code on the usage of nextLine() method
 * of Scanner class to print the contents of a file line by line
 */

public class ScannerNextLine {

	public static void main(String[] args) throws FileNotFoundException {
		// Declare File object
		File file = new File("E:/tmp/java/tutorial/scanner/example.txt");
		// initialize the scanner
		Scanner scan = new Scanner(file);
		// iterate through the file line by line
		while(scan.hasNextLine()){
			// print the contents of a file by line
			System.out.println(scan.nextLine());
		}
		// close the scanner object;
		scan.close();

	}
}

The following are the contents of the file:

****************
albert einstein
william victor salvatore
alan cayetano
****************

Sample Output :

Running the nextLine() method example source code of Scanner class will give you the following output

java scanner nextline method example

java scanner nextline method example

Exception Scenario :

Exception in thread "main" java.util.NoSuchElementException: No line found
	at java.util.Scanner.nextLine(Unknown Source)
	at com.teknoscope.java.tutorial.scanner.ScannerNextLine.main(ScannerNextLine.java:25)

Exception in thread "main" java.lang.IllegalStateException: Scanner closed
	at java.util.Scanner.ensureOpen(Unknown Source)
	at java.util.Scanner.findWithinHorizon(Unknown Source)
	at java.util.Scanner.nextLine(Unknown Source)
	at com.teknoscope.java.tutorial.scanner.ScannerNextLine.main(ScannerNextLine.java:27)

Similar Method :

  • N/A

Suggested Reading List :

References :