Home Tutorial Java Core Files Java file scanner

 
 

Java file scanner
Posted on: July 27, 2006 at 12:00 AM
In this section, you will learn how to read a file using Scanner class.

Java file scanner

In this section, you will learn how to read a file using Scanner class.

Description of code:

J2SE5.0 provides some additional classes and methods that has made the programming easier. In comparison to any input - output stream, the class java.util.Scanner perform read and write operations easily. It also parses the primitive data. Scanner class gives a great deal of power and flexibility.

You can see in the given example, we have created a Scanner object and parses the file through the File object. It then calls the hasNextLine() method. This method returns true if another line exists in the Scanner's input until it reaches the end of the file. The nextLine() method returns a string on a separate line  until it reaches the end of the file.

Here is the code:

import java.io.*;
import java.util.Scanner;

public class FileScanner {
	public static void main(String[] args) throws Exception {
		File file = new File("C:/file.txt");
		Scanner scanner = new Scanner(file);
		while (scanner.hasNextLine()) {
			String line = scanner.nextLine();
			System.out.println(line);
		}
	}
}

In  the above code, instead of any input-output stream, we have used Scanner class to read the file.

Output:

Hello World,

All glitters are not gold.

Related Tags for Java file scanner:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.