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 line to be read using Java code for parsing
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,
- How to Get List of All Country Codes in Java Using Locale Class
- Unsupported major.minor version 52.0 in java
- Java - How to set custom thread name?
- Get the current timestamp in Java
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- [fix] NullPointerException Cannot Invoke findById because Repository is null - Java Spring
- java: unclosed string literal [Error]
- Convert Java Byte Array to String with code examples
- Error: Can not find the tag library descriptor for
- Java 8 - Convert List to Map Examples
- Java - Calculate time taken for the code to execute in milliseconds or nanoseconds
- Fix java.net.ProtocolException: Invalid HTTP method
- Java: Convert Stream to List
- Java equals method - Tutorial
- List of Java JDBC Database Driver Jars, Classes and URLs Details
- Read YAML file Java Jackson Library
- How to display Java Date Time timezone GMT/UTC offset using SimpleDateFormat
- List of Java Keywords
- Enable JSON Pretty Print in Java Jackson
- How to Word-Warp Console logs in IntelliJ
- Convert Map to List in Java 8 using Stream API
- Create a Directory using Java Code
- Ways to Convert Integer or int to Long in Java
- [Program] How to read three different values using Scanner in Java
- Java JDBC Example with Oracle Database Driver Connection
More Posts:
- CentOS Cannot find a valid baseurl for repo base7x86_64 yum - HowTos
- Clone a particular remote brach using git clone command - Git
- How to Right Click on Mac Desktop? - MacOS
- List of Java JDBC Database Driver Jars, Classes and URLs Details - Java
- Auto Refresh Webpage after every x Second or Minute using Meta Tag? - Html
- List of jar files for Jax-ws (SOAP) based Java Web Services - Java
- [Fix] Docker Error response from daemon: manifest for :latest not found: manifest unknown - Docker
- [Android Studio] failed to find Build Tools revision 23.0.0 rc1 - Android-Studio