Thursday, 16 June 2016

Reading file in Java using Scanner

Though reading file using BufferedReader remains one of the most used way to read a file but there are other ways to read a file too. Like Scanner class, which was added in Java 5, can be used to read a file.

Scanner is used widely to read input from console as it has a constructor which takes InputStream as argument. But it also has a constructor which takes File as argument and also has methods hasNextLine() and nextLine() to find if there is another line of input and reading the line from input respectively.

One other benefit of using Scanner is it has useDelimiter() method, using this method file delimiter can be set thus making Scanner a good choice for reading and parsing CSV, tab delimited or pipe symbol separated files.

Example code

In the example a File instance is created by passing the file name (file which has to be read) as argument. Then that file instance is passed to Scanner class object. Then file is read using the nextLine() method of the Scanner class.

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

public class ScannerRead {

 public static void main(String[] args) {
  File file = new File("G:\\Temp.txt");
  Scanner sc;
  try {
   sc = new Scanner(file);
   // Check if there is another line of input
   while(sc.hasNextLine()){
    String str = sc.nextLine();
    System.out.println("" + str);
   
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  

 }

}

That's all for this topic Reading file in Java using Scanner. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to convert a file to byte array
  2. How to read file from the last line in Java
  3. Reading file in Java using BufferedReader
  4. How to create PDF from XML using Apache FOP

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment