CSV File Read Line By Line
In the post I am going to explaining CSV file read line by line by using opencsv jar file. You can see what is CSV file?.
Before going to write java program we need to download opencsv jar file.
Find the below sample data and save it in the format of csv file extension.
How to create csv file
- Open note pad
- Paste the below data into note pad
- Save it as like “OpenCsvRead.csv” in the double quote as file name.
FIRSTNAME,LASTNAME,AGE Narayana,Ragi,30 Kumar,Chitra,50 Swamy,Bathala,40
Find the below java program will read the above data line by line with splitting comma separated values by default means that no need to mention the comma in the program. It will read csv file line by line, in each line values will be splitted and putting into string array and the array will be iterated like one iteration for one line.
package com.narayanatutorial.opencsv; import au.com.bytecode.opencsv.CSVReader; import java.io.FileReader; public class OpenCsvReadLineByLine { public static void main(String args[]) { String csvFilename = "D:/narayanatutorial/SampleFiles/OpenCSVRead.csv"; try { CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); String[] csvrow = null; while ((csvrow = csvReader.readNext()) != null) { System.out.println(csvrow[0] + " # " + csvrow[1] + " # " + csvrow[2]); } } catch (Exception e) { System.out.println("exception :" + e.getMessage()); } } }
Copy the above java program into your IDE and execute then see the output as follows
Output
FIRSTNAME # LASTNAME # AGE Narayana # Ragi # 30 Kumar # Chitra # 50 Swamy # Bathala # 40
you can find the above sample program in the github. If you have git account you can download from github and other sample programs also available and find the below github link to download. We used Netbeans IDE to develop sample programs. So you can directly import into Netbeans if you are having Netbeans else create sample project in your IDE and replace src folder.
Git link
I hope you understand CSV File Read Line By Line by using opencsv jar file.
Hello! I am Narayanaswamy founder and admin of narayanatutorial.com. I have been working in the IT industry for more than 12 years. NarayanaTutorial is my web technologies blog. My specialties are Java / J2EE, Spring, Hibernate, Struts, Webservices, PHP, Oracle, MySQL, SQLServer, Web Hosting, Website Development, and IAM(ForgeRock) Specialist
I am a self-learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.