Share on Google+Share on Google+

Java file scanner

Advertisement
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.

Advertisements

Advertisement

Posted on: July 27, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.