
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Read Data from a CSV File in Java
A CSV stands for Comma Separated Values. In a CSV file, each line contains words that are separated with a comma(,) and it is stored with a .csv extension.
We can read a CSV file line by line using the readLine() method of BufferedReader class. Split each line on comma character to get the words of the line into an array. Now we can easily print the contents of the array by iterating over it or by using an appropriate index.
CSV File
Example
import java.io.*; public class CSVReaderTest { public static final String delimiter = ","; public static void read(String csvFile) { try { File file = new File(csvFile); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line = ""; String[] tempArr; while((line = br.readLine()) != null) { tempArr = line.split(delimiter); for(String tempStr : tempArr) { System.out.print(tempStr + " "); } System.out.println(); } br.close(); } catch(IOException ioe) { ioe.printStackTrace(); } } public static void main(String[] args) { // csv file to read String csvFile = "C:/Temp/Technology.csv"; CSVReaderTest.read(csvFile); } }
Output
"JAVA" "PYTHON" "JAVASCRIPT" "SELENIUM" "SCALA"
Advertisements