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,
- Java XML-RPC 3.1.x based web service example
- List of jars required for Struts2 project
- list of jars required for hibernate 4.x.x
- How to create StackOverflow error in java
- Tutorial Java SOAP WebServices JAS-WS with Eclipse J2EE IDE and Tomcat Server Part 1
- import servlet API to eclipse project (javax.servlet cannot be resolved error)
- [Solved] com.sun.xml.ws.transport.http.servlet.WSServletContextListener ClassNotFoundException
- Convert String to int in Java
- JSP Hello World Program Tutorial with Eclipse and Tomcat Server
- SharePoint Open in the client application document opens in browser
- Java: TimeZone List with GMT/UTC Offset
- Struts2 : java.lang.ClassNotFoundException: org.apache.commons.fileupload.RequestContext
- Remove Trailing zeros BigDecimal Java
- [Solution] Java Error Code 1603. Java Update did not complete.
- Maven Eclipse (M2e) No archetypes currently available
- error: file not found: HelloWorld.java
- Exception in thread main java.lang.NoClassDefFoundError: package javaClass
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to check if Java main thread is alive
- [Hibernate] The method buildSessionFactory() from the type Configuration is deprecated
- Java XML-RPC java.net.BindException: Address already in use
- Eclipse : The type java.lang.CharSequence cannot be resolved. Indirectly referenced from required .class files
- Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end users experience
- Eclipse : A java Runtime Environment (JRE) or Java Development kit (JDK) must be available
- List of jar files for Jax-ws (SOAP) based Java Web Services
- [Java Threads] Should we extend Thread Class or implement Runnable interface
- Maven Unsupported major.minor version 51.0
- hibernate.cfg.xml Configuration and Mapping xml Example
- How to verify if java is installed on the computer and get version detail
- Unhandled exception type InterruptedException : Java Threads
- XmlRpcException ConnectException connection refused error
- Error: Unable to access jarfile jarFileName.jar file [Windows]
- BeanDefinitionStoreException IOException parsing XML document from class path resource [spring.xml]
- How to serialize-deserialize an object in java
- List of Java Keywords
- Simple Struts 2 Tutorial in eclipse with tomcat 7 server
- Struts 2 Hello World Example in Eclipse
- Your JBoss Application Server 7 is running However you have not yet added any users to be able to access the admin console
- List of Java versions
- Create simple struts2 project using maven commands
- Struts 2 : There is no Action mapped for namespace [/] and action name [form] associated with context path [/proj]
- Error: Can not find the tag library descriptor for
- connection.url property value in hibernate.cfg.xml for mysql
- Unbound classpath container: JRE System Library [JavaSE-1.7]
- Setting Java_Home Environment variable on Windows Operating System
More Posts:
- Create Custom Android AlertDialog - Android
- Copy Text to Android Clipboard Programmatically ClipboardManager - Android
- Facebook Down Will Be Back Soon - Facebook
- How to check installed Eclipse version 32-bit or 64-bit - Eclipse
- How to create an Autocomplete Android EditText Example - Android
- How to display Toast on Button Click : Android - Android
- Two Buttons next to each other in Android Layout - Android
- JSON Datatypes : Tutorial - Json-Tutorial
- Eclipse : Workspace was written with an older version of the product and will be updated - Eclipse
- JavaScript : redirect page to other url - Android
- Android Error Unexpected cast to Button: layout tag was FrameLayout - Android
- [Solved] SharePoint System.IO.FileNotFoundException was unhandled - SharePoint
- Fibonacci series from 1 to 500 table - Html
- The author stylesheet specified in tag script is too long - document contains 21759 bytes whereas the limit is 10000 bytes - Html
- Facebook Graph API Unavailable - Facebook