Blog

Read and Display a CSV File in Java

By  
Tarek Oraby
Tarek Oraby
·
On Sep 9, 2021 9:56:40 AM
·

This guide demonstrates how to import a CSV file in Java and display it in a data grid.

Tutorial feature image

In this guide, we create a web app that enables users to upload a CSV file to the server, where the file content is processed, and displayed back to the user’s UI inside a data grid. The web app is developed entirely in Java using Vaadin Flow (no HTML or JavaScript involved). You can explore the full source code on GitHub

What You Need

  • About 5 minutes
  • JDK 8 or later 

Import a Starter Project

  1. Download a starter project by clicking the following link:
    DOWNLOAD A STARTER
  2. Unzip the starter and open the project in your favorite IDE.

Add OpenCSV Dependency

Before we start, we need to add a dependency on OpenCSV, which is the library we’ll use to parse the CSV files. 

In the dependencies section of pom.xml, add the following dependency:

<dependency>
  <groupId>com.opencsv</groupId>
  <artifactId>opencsv</artifactId>
  <version>5.5.1</version>
</dependency>

Create the View

Now we create the view that holds the upload component (through which users upload the CSV file) and the grid (that will display the contents of the CSV file once processed on the server). This view is a Vaadin VerticalLayout, and it is made accessible to the end user via the @Route annotation (in this case, it would be accessible via the /csv route).


import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.exceptions.CsvException;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.component.upload.receivers.MemoryBuffer;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.shared.util.SharedUtil;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

@Route("csv")
public class CSVView extends VerticalLayout {
  private Grid<String[]> grid = new Grid<>();

   public CSVView() {
      MemoryBuffer buffer = new MemoryBuffer();
      Upload upload = new Upload(buffer);
      upload.setAcceptedFileTypes(".csv");
      upload.addSucceededListener(e -> {
          displayCsv(buffer.getInputStream());
      });
      add(upload, grid);
  }

   private void displayCsv(InputStream resourceAsStream) {
      CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
      CSVReader reader =
              new CSVReaderBuilder(new InputStreamReader(resourceAsStream)).withCSVParser(parser).build();
      try {
          List<String[]> entries = reader.readAll();
          String[] headers = entries.get(0);
          grid.removeAllColumns();

          for (int i = 0; i < headers.length; i++) {
              int colIndex = i;
              grid.addColumn(row -> row[colIndex])
                      .setHeader(SharedUtil.camelCaseToHumanFriendly(headers[colIndex]));
          }

           grid.setItems(entries.subList(1, entries.size()));
      } catch (IOException | CsvException e) {
          e.printStackTrace();
      }
  }
}

Run the Application

To run the project from the command line, type mvnw spring-boot:run (on Windows), or ./mvnw spring-boot:run (on macOS or Linux). 

Then, in your browser, open http://localhost:8080/csv.

Summary

Congratulations! You have created a web app that enables users to upload a CSV file to the server, which is displayed back to the UI in a data grid. And you did it in pure Java, without the need to use HTML or JavaScript, or to expose REST services, or to think about HTTP requests, responses, and filter chains.

You can explore the full source code on GitHub.

 

See Also