×

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into and exported from programs like Microsoft Excel and Microsoft Office that store data in tables. A delimiter identified and separated different data tokens in a CSV file.We use the CSV file format when we move tabular data between programs that natively operate on incompatible formats. In Java, you can read CSV files in the following ways. A comma (,) serves as a CSV file's default separator.

There are the following ways of printing an exhibit in Java:

Using the OpenCSV API and the Java Scanner class's String.split() method

  1. Java Scanner class
  2. Java String.split() method
  3. Using OpenCSV API

A CSV (Comma-Separated Values) file is similar to a regular plain text file in that it stores data by columns and uses a delimiter (usually a comma ",")

OpenCSV is a Java library for parsing CSV files. OpenCSV allows you to performthe basic CSV operations you need. OpenCSV currently only supports Java 7 as the minimum supported version. Use OpenCSV to process CSV files in Java, as the Java programming language does not have native support for efficiently processing CSV files.

The CSV file can be read in two ways:

  • Line by line, read the data: Let's examine each CSV file line one at a time. Bypassing the filereader object of the CSV file, we must first construct and initialize the CSVReader object before we can read data line by line.After that, we must use the CSVReader object's readNext() method to read the data line by line, as shown in the code below.
// Java code to illustrate reading a
// CSV file line by line
public static void readDataLineByLine(String file)
{
    try {
        // Create an object of filereader
        // class with CSV file as a parameter.
FileReaderfilereader = new FileReader(file);


        // create csvReader object passing
        // file reader as a parameter
CSVReadercsvReader = new CSVReader(filereader);
String[] nextRecord;
        // we are going to read data line by line
        while ((nextRecord = csvReader.readNext()) != null) {
            for (String cell :nextRecord) {
System.out.print(cell + "\t");
            }
System.out.println();
        }
    }
    catch (Exception e) {
e.printStackTrace();
    }
}
  • Immediately read all data: ThereadNext() method is used to read the CSV records one at a time.Additionally, CSVReader provides a readAll() method for simultaneously reading all records into a List.
List allData = csvReader.readAll();

As can be seen in the codes' output, when we read a csv file by default, the header is not ignored.When creating CSVReader, we can specify a start line to skip the first item in the list.

CSVReadercsvReader = new CSVReaderBuilder(reader).withSkipLines(1).build();
// Java code to illustrate reading a
public static void readAllDataAtOnce(String file) {
    try {
        // Create an object of file reader
        // class with CSV file as a parameter.
FileReaderfilereader = new FileReader(file);
        // create csvReader object and skip first Line
CSVReadercsvReader = new CSVReaderBuilder(filereader)
.withSkipLines(1)
.build();
        List<String[]>allData = csvReader.readAll();
        // print Data
        for (String[] row : allData) {
            for (String cell : row) {
System.out.print(cell + "\t");  }
System.out.println();}   }
    catch (Exception e) {
e.printStackTrace();
}   }

Reading a CSV file with a different separator a delimiter other than a comma, such as a pipe, semicolon, or other character, can be used to separate CSV files. The following example demonstrates how to read CSV file data separated by a semicolon.

Example of a CSV file separated by semicolons:

/ Java code to illustrate
// Reading CSV File with different separator
public static void readDataFromCustomSeparator(String file)  {
    try {
        // Create an object of file reader class with a CSV file as a parameter.
FileReaderfilereader = new FileReader(file);
        // create a csvParser object with
        // custom separator semi-colon
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
        // create csvReader object with parameter
        // filereader and parser
CSVReadercsvReader = new CSVReaderBuilder(filereader)
.withCSVParser(parser)
.build();
        // Read all data at once
        List<String[]>allData = csvReader.readAll();
        // Print Data.
        for (String[] row : allData) {
            for (String cell : row) {
System.out.print(cell + "\t");}
System.out.println();  }  }
    catch (Exception e) {
e.printStackTrace();
    }  }

Related Topics

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.