How to Read Delimited File in Java

If you have to read delimited file in Java and parse it then you can do it using the following two ways-

1- Using Scanner class with useDelimiter() method.
2- Read file using BufferedReader line by line and then split each line using split() method.

Using Scanner class to read delimited file in Java

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches white space. The scanner can also use delimiters other than white space for that useDelimiter() method is used. Let’s see some examples of using Scanner class to read delimited file in Java.

Reading CSV file using Scanner in Java

Here is an example CSV file which denotes Account From, Account To and Amount Transferred.

1001,1003,2000
1006,2004,3000
1005,1007,10000

Which you want to read using Scanner class and parse it to display the fields.

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

public class ReadDelimited {
  public static void main(String[] args) {
    Scanner sc = null;
    try {
      sc = new Scanner(new File("D:\\acct.csv"));

      // Check if there is another line of input
      while(sc.hasNextLine()){
        String str = sc.nextLine();
        // parse each line using delimiter
        parseData(str);
      }
    } catch (IOException  exp) {
      // TODO Auto-generated catch block
      exp.printStackTrace();
    }finally{
      if(sc != null)
        sc.close();
    }	  		
	}
	
  private static void parseData(String str){	
    String acctFrom, acctTo, amount;
    Scanner lineScanner = new Scanner(str);
    lineScanner.useDelimiter(",");
    while(lineScanner.hasNext()){
      acctFrom = lineScanner.next();
      acctTo = lineScanner.next();
      amount = lineScanner.next();
      System.out.println("Account From- " + acctFrom + " Account To- " + acctTo + 
       " Amount- " + amount);  
    }
    lineScanner.close();
  }
}

Output

Account From- 1001 Account To- 1003 Amount- 2000
Account From- 1006 Account To- 2004 Amount- 3000
Account From- 1005 Account To- 1007 Amount- 10000

Reading pipe (|) delimited file in Java using Scanner

Here is another example Java program showing how you can read pipe delimited data using Scanner in Java.

1001|1003|2000
1006|2004|3000
1005|1007|10000

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

public class ReadDelimited {
  public static void main(String[] args) {
    Scanner sc = null;
    try {
      sc = new Scanner( new File("D:\\test.txt"));
      
      // Check if there is another line of input
      while(sc.hasNextLine()){
        String str = sc.nextLine();
        // parse each line using delimiter
        parseData(str);
      }
     
    } catch (IOException  exp) {
      // TODO Auto-generated catch block
      exp.printStackTrace();
    }finally{
      if(sc != null)
        sc.close();
    }	  		
  }
	
  private static void parseData(String str){	
    String acctFrom, acctTo, amount;
    Scanner lineScanner = new Scanner(str);
    lineScanner.useDelimiter("\\|");
    while(lineScanner.hasNext()){
      acctFrom = lineScanner.next();
      acctTo = lineScanner.next();
      amount = lineScanner.next();
      System.out.println("Account From- " + acctFrom + " Account To- " + acctTo + 
         " Amount- " + amount);  
    }
    lineScanner.close();
  }
}

Output

Account From- 1001 Account To- 1003 Amount- 2000
Account From- 1006 Account To- 2004 Amount- 3000
Account From- 1005 Account To- 1007 Amount- 10000

Since pipe symbol is a reserved character you do need to escape it, that is why lineScanner.useDelimiter(“\\|”); is used.

Using split() method to split delimited data

Another way to read delimited file in Java is to read file line by line, you can use BufferedReader to read the file and then split delimited data using split method. If we take the same pipe delimited file as used above then the Java example is as follows.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadDelimited {
  public static void main(String[] args) {
    BufferedReader br = null;
    try{
       String strLine;
       //FileReader instance wrapped in a BufferedReader
       br = new BufferedReader(new FileReader("D:\\test.txt"));
       
       while((strLine = br.readLine()) != null){
         parseData(strLine);
       }
    }catch(IOException exp){
      System.out.println("Error while reading file " + exp.getMessage());
    }finally {
      try {
        // Close the stream
        if(br != null){
          br.close();
        }
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }  		
  }
	
  private static void parseData(String str){	
    String acctFrom, acctTo, amount;
    // parsing using split method
    String[] data = str.split("\\|");
    System.out.println("Account From- " + data[0] + " Account To- " + data[1] + 
         " Amount- " + data[2]);  
  }
}

Output

Account From- 1001 Account To- 1003 Amount- 2000
Account From- 1006 Account To- 2004 Amount- 3000
Account From- 1005 Account To- 1007 Amount- 10000

Related Posts

That’s all for the topic How to Read Delimited File in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.