Wednesday, January 17, 2018

Reading File in Java Using Scanner

Though reading file using BufferedReader remains one of the most used way to read a file in Java but there are other ways too like using Scanner class. This post shows how you can read a file in Java using Scanner class.

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. Using that constructor you can read a file in Java using Scanner.

One other benefit of using Scanner is that it has a 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 in Java.

Java program to read a file using Scanner

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 line by line 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!

>>>Return to Java Programs Page


Related Topics

  1. How to Convert a File to Byte Array
  2. How to Read Properties File in Java
  3. Reading All Files in a Folder - Java Program
  4. How to Untar a File - Java Program
  5. How to Create PDF From XML Using Apache FOP

You may also like-

  1. How to Create Deadlock in Java Multi-Threading - Java Program
  2. How to Swap or Exchange Two Numbers Without Using Any Temporary Variable - Java Program
  3. Getting All The Schemas in a DB - Java Program
  4. Find Largest And Smallest Number in The Given Array - Java Program
  5. Abstraction in Java
  6. How ArrayList Works Internally in Java
  7. ReentrantLock in Java Concurrency
  8. What is Dependency Injection in Spring