Line by Line reading from a file using Scanner Class

In this section, you will get to know about reading line by line a text file using java.util.Scanner class.

Line by Line reading from a file using Scanner Class

Line by Line reading from a file using Scanner Class

In this section, you will get to know about reading line by line a text file using java.util.Scanner class.

Class java.util.Scanner

The java.util.Scanner class uses the regular expression to parse the primitive types and strings. Using delimiters, it breaks the input into tokens. The default delimiter is white space. In absence of external synchronization ,a Scanner class is not considered safe for the multithreaded environment.

Constructors of the Scanner Class

Given below the list of constructors of the Scanner class, which produces the scanned value from a specific source :

  • Scanner(File source)

  • Scanner(File source, String charsetName)

  • Scanner(InputStream source)

  • Scanner(InputStream source, String charsetName)

  • Scanner(Readable source)

  • Scanner(ReadableByteChannel source)

  • Scanner(ReadableByteChannel source, String charsetName)

  • Scanner(String source)

EXAMPLE

In the below example, we are reading line by line using the Scanner class :

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

public class ReadFileLineByLine {
	
	public static void main(String[] args) {
	
		// Provide Source Location to read file
		File file = new File("data.txt");
		
		try {
		
		Scanner scan = new Scanner(file);
		
		while (scan.hasNextLine()) {
			String scannedline = scan.nextLine();
			System.out.println(scannedline);
		}
		scan.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	
	}
}

In the above code,  Scanner class constructor is used to bring out the values scanned from the specified file. The first Scanner method used here is hasnextLine() which return true, if there exist a line to read. If next line doesn't exist, this method returns false. The second method used here is nextline(), which return the current line. If the file doesn't existed at location provided, it will throw exception of type FileNotFoundException and print it on the console. The above code will display content of the file , line by line, on the console.

Scanner class is also very useful in reading a text file line by line. The hasNextLine() method of the Scanner class is used to find if there more line available in file. The nextLine() method is used to read the next line from the file.

The java.util.Scanner class is very useful class in the java.util package. It works as a simple text scanner and can be used to parse primitive types and strings. It uses the regular expressions for parsing the data.