A CSV file is a comma-separated text file with double quotes as escape characters for a comma in a string element. In this tutorial, we will see how we can parse a CSV file using Java code example,
package com.code2care.tutorials;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
*
* Java Code to process CSV file.
*
* @author Code2care Tutorials
*
*/
public class JavaArrayToArrayList {
public static void main(String[] args) throws IOException {
String csvFilePath = "C:\\Users\\Code2care\\Desktop\\file\\data.csv";
String line = null;
BufferedReader bufferedReader = null;
try {
File csvFile = new File(csvFilePath);
FileReader fileReader = new FileReader(csvFile, StandardCharsets.UTF_8);
bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] csvLineElements = line.split(",");
for (int i = 0; i < csvLineElements.length; i++) {
System.out.println(csvLineElements[i]);
}
}
}
catch (IOException e) {
System.out.println("Error Occured while parsing csv file.");
e.printStackTrace();
} finally {
bufferedReader.close();
}
}
}
CSV text File:
SrNo,Name,Score
1,Mike,200
2,Alex,400
3,Steve,500
4,Alen,530
5,Kevin,108
Steps to parsing a CSV file using Java Code
- Create a String object with he absolute path of the csv file to be read,
- Create a FileReader class object, this class is used to reads text from character files using a default buffer size. Note if you are dealing with UTF-8 encoding make sure you use constructor FileReader(File file, Charset charset). Note that FileReader is meant for reading streams of characters to read streams of raw bytes you should use FileInputStream.
- Create an object of BufferedReader to read text from a character-input stream, we pass the FileReader object to its constructor.
- Now using a while loop iterate while bufferedReader.readLine() is not null.
- In the while loop, read the elements of the line by splitting the line by comma regex.
- Now you have access to each element of a CSV file.
More Posts related to Java,
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
More Posts:
- How to create alias in macOS - MacOS
- Sharepoint Server 2016 installation Prerequisites with download links - SharePoint
- Multiple ways to Convert tabs with spaces in Notepad++ - NotepadPlusPlus
- How to Auto Fill Down in Excel for Mac - MacOS
- Save webpage as pdf in Google Chrome for Mac OS X - Mac-OS-X
- Nano Undo/Redo Keyboard Shortcuts - Linux
- How to Save Jupyter Notebook as PDF - Python
- Mac: How to Open Android Studio from Terminal - MacOS