How to Read CSV File in Java


Sometimes we get requirements like to load CSV files in Java Project.
Where need to convert each column and row values in Java Objects using POJO class.

The CSV stands for Comma-Separated Values, this is a very simple file where each element are separated by comma(,). CSV can be directly open in any text editor or in Microsoft Excel.

To make this project we need a POJO class of columns present in the CSV file.
In this tutorial, we are going to use the Customer details CSV file as below.


customer details present in csv file


Here we have a Customer ID, Name, City, Pincode, and State Code.
We may have more than that data and might be there are multiple fields that are blank.
So ID-103 having Customer Name - Geetha having blank City name, same with others as well for other fields.

We are going to handle these scenarios as well using the try-catch block.

In the beginning, we will create a Customer Pojo class as below.

File Location: src/com/slash/code/Customer.java


package com.slash.code;

public class Customer {

 private int custId;
 private String custName;
 private String custCity;
 private int pinCode;
 private String stateCode;
 
 public Customer(){}
 public Customer(int custId, String custName, String custCity, int pinCode,
   String stateCode) {
  super();
  this.custId = custId;
  this.custName = custName;
  this.custCity = custCity;
  this.pinCode = pinCode;
  this.stateCode = stateCode;
 }
 
 @Override
 public String toString() {
  return "Customer [custId=" + custId + ", custName=" + custName
    + ", custCity=" + custCity + ", pinCode=" + pinCode
    + ", stateCode=" + stateCode + "]";
 }

 public int getCustId() {
  return custId;
 }
 public void setCustId(int custId) {
  this.custId = custId;
 }
 public String getCustName() {
  return custName;
 }
 public void setCustName(String custName) {
  this.custName = custName;
 }
 public String getCustCity() {
  return custCity;
 }
 public void setCustCity(String custCity) {
  this.custCity = custCity;
 }
 public int getPinCode() {
  return pinCode;
 }
 public void setPinCode(int pinCode) {
  this.pinCode = pinCode;
 }
 public String getStateCode() {
  return stateCode;
 }
 public void setStateCode(String stateCode) {
  this.stateCode = stateCode;
 }  
}

So here in Customer Pojo, we will have the required properties, their getters, and setters, default constructor, parameterized constructor. toString() is for printing objects using System.out.println() function.

Now we will have our main function where the program gets the start, and execute required functionality.

File Location: src/com/slash/code/ReadCSV.java

package com.slash.code;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class ReadCSV {

 public static void main(String[] args) {
  List<Customer> custList = getCustDetails("D:\\Test\\CustDetails.csv");
  for(Customer cust:custList){
   System.out.println(cust);
  }
 }

 private static List<Customer> getCustDetails(String file) {
  List<Customer> custList =new ArrayList<>();
  Path pathToFile = Paths.get(file);
  try(BufferedReader br = Files.newBufferedReader(pathToFile)){
   String row = br.readLine();
   while(row!=null){
    String [] attributes = row.split(",");
    Customer cust = getOneCustomer(attributes);
    custList.add(cust);
    row=br.readLine();
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  return custList;
 }

 private static Customer getOneCustomer(String[] attributes) {
  int custId,pinCode;
  String custName,custCity,stateCode;
  try{
   custId = Integer.parseInt(attributes[0]);
  }
  catch(Exception e){custId = 0;}
  try{
   custName = attributes[1];
  }
  catch(Exception e){custName = null;}
  try{
   custCity = attributes[2].equalsIgnoreCase("")?null:attributes[2];
  }
  catch(Exception e){custCity = null;}
  try{
   pinCode = Integer.parseInt(attributes[3]);
  }
  catch(Exception e){pinCode = 0;}
  try{
   stateCode = attributes[4];
  }
  catch(Exception e){stateCode = null;}
  Customer cust = new Customer(custId,custName,custCity,pinCode,stateCode);  
  return cust;
 }
}


Now in ReadCSV.java file, we have three functions as below:
  1. main()
    • To start the execution of the program, where we are passing file location and getting results in a list of the customers.
    • We are iterating customers list one by one here as well.

  2. getCustDetails(String file)
    • It will take file location as input and returns the list of customers present in that file.
    • It will split the column in String array and send it to getOneCustomer(String[] attributes) function.

  3. getOneCustomer(String[] attributes)
    • It will take customer details and check if it throws any exceptions and initialize it to null or 0.
    • It returns one customer object with having one column data in it.
So now you just need to run this code and you will get your required output, please let me know in case of any issue.

 Youtube video link for your reference:



Comments

Post a Comment

Popular posts from this blog

How to read XLS and XLSX Excel files in Java

SQLite Database CRUD Operation in Ionic 4