How To Read CSV Files in Java as Maven Project

Many of us have problems reading CSV files in Java but not anymore!. In this guide, I will share how to read CSV files as Maven Project.

For creating a Maven project:

  • In your Eclipse IDE, click on File > New > Project... > Maven >Maven Project > Next > Check "Create a simple project" checkbox.
  • Under Group Id: The name could be anything. It is same as any package name. E.g. in.sumitkp
  • Under Artifact Id: Same as above It is same as any project name. E.g. maven-demo1
  • Let the Version be the default.
  • Under Name: Give the name for your project
  • Click Finish.

In your Project Explorer, all the necessary files will be automatically generated. Inside the root folder, there will be an XML file auto-generated called pom.xml.

About pom.xml:
  • POM stands for Project Object Model
  • It is an XML file that contains information about the project and configuration details used by Maven to build the project.
  • When running a task, Maven looks for the pom.xml file in the directory. It reads the file, gets the needed configuration information, then executes the goal.
So, pom.xml is the file where all the needed dependencies will be stored for reading the CSV files.
Under </version> tag, type <dependencies>  </dependencies>. Under this <dependencies> open tag, we need to paste some repository code for CSV reader. For this go to Maven Repository: Search/Browse/Explore (mvnrepository.com), in the search box, type opencsv and press Enter key.

Next page, all opencsv related result will come. Now, click on the top result for OpenCSV (com.opencsv). Scroll down, under Central repository, look for the latest released version. Right now, it is 5.5.2. On next page, scroll down, under Maven tab, click on the text box under it. The whole code of this repository will be copied to your system clipboard. If it doesn't then select whole code with your mouse and CTRL+C it.


Paste this code in pom.xml file under <dependencies>. Make sure this repository is enclosed between the dependencies tag.

EDIT 1:
Some people are getting a lot of exceptions while running just with OpenCSV, so try adding of Apache too.  
Replace everything under <dependencies>  </dependencies> with following code. 
<dependencies>
<!--to read csv files -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.9.0</version>
</dependency>
<dependency>
  <groupId>com.opencsv</groupId>
  <artifactId>opencsv</artifactId>
  <version>5.5.2</version>
</dependency>
</dependencies>

After you paste this, a new folder under root folder of your project will be created as Maven Dependencies. Here, all the needed jar files of OpenCSV will be uploaded. Make sure you have a working internet connection to do this. If it doesn't come, right-click on your project folder > Maven > Update Project.

Now, how to read CSV files. Let's come to the final thing!
In your project folder, right-click on src/main/java to create a class readCSV.java. Right-click on your project folder > New > Folder. Name this new folder as csvDataFiles. This folder will store all your .csv files.

Necessary packages to import:
  1. import java.io.*;
  2. import java.util.*;
  3. import com.opencsv.*;

Code for readCSV.java :
*Type will be name of class in this case: Product
public static void readCSVdata() throws IOException, CsvValidationException {
  File dir = new File("csvDataFiles"); //folder directory where all csv files are stored
  File[] files = dir.listFiles(); //returns array of files in the specified folder
  Reader reader = null; //initiating the value of reader with null
  /*
   * creating an empty arraylist
   */
  ArrayList < Type> arrayList = new ArrayList < Type> (); //here Type is the type of data you would be storing.
  /*
   * fetching all the files from the array of files
   */
  for (File file: files) {
    try {
      reader = new BufferedReader(new FileReader(file));
      CsvToBean < Type> csvReader = new CsvToBeanBuilder < Type> (reader).withType(Type.class).withSeparator('|').build();
      Iterator < Type> itr = csvReader.iterator();
      while (itr.hasNext()) {
        Product p1= itr.next();
      }
    } catch (IOException e) {
      System.out.println(e);
    } finally {
      if (reader != null) {
        reader.close();
      }
    }
  }

}

Now, suppose you want to store data from csv files as an object. Then create under class under src/main/java as Product.java.

If you check the official OpenCSV user guide at: http://opencsv.sourceforge.net/, and read under opencsv – (sourceforge.net) (Annotating by header name), you will find how to do it. 

Now, it will be time consuming if you have to write getters and setters for all these variables. So on your Product.java, right-click > Source or press ALT + SHIFT + S > Generate Getters and Setters.. > Click Select All > Generate .


















Now in readCSV.java file, you are retrieving data from .csv files and storing them into object of Product class. Now you can use different get methods for different operations.
Suppose you need to get name of one such product, you can use p1.getName();

If you have any query, you can comment below.

Comments

Popular

How To Create MySQL Table with SequelizeJS

How To Create A Hibernate Project in Maven