Monday, May 21, 2018

Reading Delimited File in Java Using Scanner

In this post we'll see how to read delimited file (like CSV) in Java using Scanner class.

A Scanner, when reading input, breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

The scanner can also use delimiters other than whitespace. Scanner class has useDelimiter() method which can be used to change default delimiter. There are two overloaded useDelimiter() methods.

  • useDelimiter(Pattern pattern)- Sets this scanner's delimiting pattern to the specified pattern.
  • useDelimiter(String pattern)- Sets this scanner's delimiting pattern to a pattern constructed from the specified String.

Java program to read CSV file using Scanner

Let's see an example where Scanner class is used to read a CSV file.

If there is a CSV file with following data-

Pride And Prejudice,Jane Austen,20.76
The Murder of Roger Ackroyd,Agatha Christie,25.67
Atlas Shrugged,Ayn Rand,34.56
Gone with the Wind,Margaret Mitchell,36.78

And you want to read and parse the line so that you have Book name, author and price as separate strings.

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

public class ScanDelimited {

 public static void main(String[] args) {
  // CSV file
  File file = new File("G:\\Temp.csv");
  Scanner sc = null;
  try {
   sc = new Scanner(file);
   // Check if there is another line of input
   while(sc.hasNextLine()){
    String str = sc.nextLine();
    parseLine(str);
   }
   
  } catch (IOException  exp) {
   // TODO Auto-generated catch block
   exp.printStackTrace();
  }
  
  sc.close();
 }
 
 private static void parseLine(String str){
  String book, author, price;
  Scanner sc = new Scanner(str);
  sc.useDelimiter(",");

  // Check if there is another line of input
  while(sc.hasNext()){
   book = sc.next();
   author = sc.next();
   price = sc.next();
   System.out.println("Book - " + book + " Author - " + author + 
     " Price - " + price);  
  }
  sc.close();
 }
}

Output

Book - Pride And Prejudice Author - Jane Austen Price - 20.76
Book - The Murder of Roger Ackroyd Author - Agatha Christie Price - 25.67
Book - Atlas Shrugged Author - Ayn Rand Price - 34.56
Book - Gone with the Wind Author - Margaret Mitchell Price - 36.78

Java program to read pipe (|) delimited file using Scanner

If you have a file where pipe is used as delimiter then you can specify that as delimiter with useDelimiter() method to read the file.

Data

Pride And Prejudice|Jane Austen|20.76
The Murder of Roger Ackroyd|Agatha Christie|25.67
Atlas Shrugged|Ayn Rand|34.56
Gone with the Wind|Margaret Mitchell|36.78
package org.netjs.examples1;

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

public class ScanDelimited {

 public static void main(String[] args) {
  // delimited file
  File file = new File("G:\\abc.txt");
  Scanner sc = null;
  try {
   sc = new Scanner(file);
   // Check if there is another line of input
   while(sc.hasNextLine()){
    String str = sc.nextLine();
    parseLine(str);
   }
   
  } catch (IOException  exp) {
   // TODO Auto-generated catch block
   exp.printStackTrace();
  }
  
  sc.close();
 }
 
 private static void parseLine(String str){
  String book, author, price;
  Scanner sc = new Scanner(str);
  sc.useDelimiter("[|]");

  // Check if there is another line of input
  while(sc.hasNext()){
   book = sc.next();
   author = sc.next();
   price = sc.next();
   System.out.println("Book - " + book + " Author - " + author + 
     " Price - " + price);  
  }
  sc.close();
 } 
}

Output

Book - Pride And Prejudice Author - Jane Austen Price - 20.76
Book - The Murder of Roger Ackroyd Author - Agatha Christie Price - 25.67
Book - Atlas Shrugged Author - Ayn Rand Price - 34.56
Book - Gone with the Wind Author - Margaret Mitchell Price - 36.78

That's all for this topic Reading Delimited 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. Reading File in Java Using Scanner
  2. Reading File in Java 8
  3. How to Read Input From Console in Java
  4. How to Read File From The Last Line in Java
  5. Creating Tar File And GZipping Multiple Files - Java Program

You may also like-

  1. Java Program to Reverse a Number
  2. Producer-Consumer Java Program Using wait notify
  3. Difference Between Two Dates - Java Program
  4. If Given String Sub-Sequence of Another String - Java Program
  5. finally Block in Java Exception Handling
  6. Callable And Future in Java concurrency
  7. Difference between HashMap and HashTable in Java
  8. Dependency Injection using factory-method in Spring