Skip to content Skip to sidebar Skip to footer

How to Read File Columns in Java

Why nosotros demand CSV Parser?

How to read csv file cavalcade by column using Java! Although this may be true, being a Developer/Automation tester CSV(Comma-Separated Values ) Parsing is the ane of frequent task which we demand in solar day to day work. Another key point, most of the complex application reports generates in CSV format and farther processed by downstream. Hence, during testing/development we need to validate CSV data in Databases, APIs or spider web portal. Also, these type of testing is quite repetitive and time consuming. So reading CSV column by column by using java code make the work more than simple and interesting.

At this indicate, this stride by step tutorial volition aid you by in writing CSV Parser.

Which CSV Parser API can be used?

Jackson information format is ane of the faster csv reader and writer either equally raw data or via data binding ot/from Objects (POJO classes). With this purpose in listen, this tutorial equally based on jackson-dataformat-csv api.

CSV Sample File

Overview of CSV data structure:

CSV Sample File
CSV Sample File

How to read a CSV File every bit Map for Key Value pair?


Map<Central, Value>

[1={EmpId=ane, Proper noun=Jack, Historic period=45, Salary=50000, City=New York}, 2={EmpId=ii, Name=Mack, Age=35, Salary=60000, City=London}, 3={EmpId=iii, Name=Andrew, Age=45, Salary=754100, City=Berlin}, 4={EmpId=four, Name=John, Age=25, Bacon=95000, Urban center=NewDelhi}, v={EmpId=five, Proper noun=Sonia, Historic period=66, Salary=74455, City=GGN}]

All things considered, at present, let'south move on to the coding part

Pre-Requisites For CSV Parser:

1. Coffee should exist installed (if non then refer this link)
2. Maven should be installed(if not then refer this link)
3. Maven Projection should be created.
4. In addition, basic thought of CSV, Map and HashMap

  • Open IDE (Intellij or Eclipse)
  • Open/Create Maven Project and click on POM.xml file
  • Add together Maven jackson-dataformat-csv dependency in with dependencies section.
          <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId>     <artifactId>jackson-dataformat-csv</artifactId>     <version>2.9.nine</version> </dependency>        
Maven jackson-dataformat-csv Dependency
Maven jackson-dataformat-csv Dependency
  • Step four: Add UTF-eight properties in Maven Project
          <properties>  <project.java.version>ane.eight</project.java.version> <projection.build.sourceEncoding>UTF-8</projection.build.sourceEncoding> <projection.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties>        
UTF-8 properties
UTF-8 properties in Maven Project
  • Stride v: Run Maven Update, Clean & Install
Maven
Maven
Install Maven
Maven install
  • Step 6: Go to src/examination/Coffee and create Util.java class and write CSV Parser Code.

Lastly, in this lawmaking, we volition create a method which will return all the CSV Data in Map. The map is used to shop Key and value. Here, we will employ the unique column as Key to identify each row and for each key, nosotros will store corresponding column values. So, in similar style, render blazon of this method is Map which has values in HashMap. By and large, as an input parameter, nosotros will pass filename (which is saved at a specific location), 1 character( for separating), and cavalcade index( which will be treated every bit the primary key).

How to read CSV file column by column using Coffee – CSV Parser Algorithm Java

  • At beginning, load CSV file in Reader class to parse CSV Information
          Reader reader = new FileReader("C:\Users\user\OneDrive\Documents\"+FileName+".csv");        
  • Secondly, identify CSV separator (comma delimitor, pipage separated etc.)
  • Create Iterator to iterate each CSV row over column and row.
          Iterator<Map<String, String>> iterator = new CsvMapper().readerFor(Map.class)        .with(CsvSchema.emptySchema().withHeader()                  .withColumnSeparator(seperator).withoutQuoteChar()).readValues(reader);        
  • Create one object of Map blazon which hold another String (Primal-Cavalcade every bit Fundamental) and Map equally as value.( for each row respective key and values).
          Map<String, Map<String, String>> CSVData = new TreeMap<String, Map<Cord, String>>();        
  • Iterate bullet 3 iterator upto each row and put values in bullet four Map i.east CSVData.
                      while(iterator.hasNext()){  keyVals = iterator.next();  Object[] keys = keyVals.keySet().toArray();                 CSVData.put(keyVals.go(keys[primaryKeyIndex]), keyVals); }        
  • Return the CSVData Map every bit parse Information.
import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import coffee.util.TreeMap; public form Util {     public static Map<String, Map<String, String>> getCSVData(char seperator, Cord FileName, int primaryKeyIndex) throws FileNotFoundException {         Map<String, Map<Cord, String>> CSVData = new TreeMap<String, Map<String, String>>();         Map<String, String> keyVals = zilch;         Reader reader = new FileReader("C:\\Users\\user\\OneDrive\\Documents\\"+FileName+".csv");         try {             Iterator<Map<String, String>> iterator = new CsvMapper().readerFor(Map.class)                     .with(CsvSchema.emptySchema().withHeader()                             .withColumnSeparator(seperator).withoutQuoteChar()).readValues(reader);             while(iterator.hasNext()){                 keyVals = iterator.adjacent();                 Object[] keys = keyVals.keySet().toArray();                 CSVData.put(keyVals.get(keys[primaryKeyIndex]), keyVals);             }         } grab (IOException east) {             e.printStackTrace();         }         render CSVData;     } }
Util.java
  • Finally, write Code to test in a higher place code.
  1. Create one map which holds data in Key (String) and values(Map- Cavalcade Name equally Key and Value).
  2. Iterate above collections over each Fundamental
  3. Go value using primary cardinal and cavalcade Proper name

Given these points, refer below lawmaking for more details:

import jdk.nashorn.internal.parser.JSONParser; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class parseCSVCode { public static void main(String[] args) throws FileNotFoundException {     Arrangement.out.println("+++++++++++++++++++++Code For CSV Parser++++++++++++");     Map<String, Map<String, String> CSV= Util.getCSVData(',',"ParseCsv",0);   Iterator<String> keys = CSV.keySet().iterator();   while (keys.hasNext()){       String primaryKey= keys.next();       Organisation.out.print("Emp Id: "+primaryKey);       System.out.print(CSV.get(primaryKey).get("Name")+" ");       Arrangement.out.impress(CSV.go(primaryKey).get("Age")+" ");       Arrangement.out.impress(CSV.get(primaryKey).become("City")+" ");       System.out.print(CSV.get(primaryKey).get("Salary")+" \n");   }     Arrangement.out.println(CSV.entrySet());  } }

[1={EmpId=ane, Proper noun=Jack, Historic period=45, Bacon=50000, City=New York}, ii={EmpId=2, Name=Mack, Age=35, Salary=60000, City=London}, 3={EmpId=3, Proper name=Andrew, Age=45, Salary=754100, City=Berlin}, 4={EmpId=4, Name=John, Historic period=25, Salary=95000, City=NewDelhi}, five={EmpId=5, Name=Sonia, Age=66, Salary=74455, City=GGN}]

To conclude, above step by footstep tutorial written to assistance you to parse CSV and use data and farther procedure. For that reason, hope this article helps you. Still if you lot face any issue feel costless contact us or accomplish united states of america on query@thoughtcoders.com

Reference: https://github.com/FasterXML/jackson-dataformats-text/tree/master/csv
https://docs.oracle.com/javase/7/docs/api/coffee/io/Reader.html

To this end, for more updates, stay continued to u.s. via Facebook and LinkedIn!

johnsonraidearan.blogspot.com

Source: https://thoughtcoders.com/how-to-read-csv-file-column-by-column-using-java/

Post a Comment for "How to Read File Columns in Java"