×

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

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

How to create an array in Java

An array is a linear data structure stores a collection of fixed number ofelements of similar type. The size of an array is specified when it is created. The array...

14 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.