Read and Parse CSV Content from an URL in Java using Apache Commons CSV

In this tutorial, we are going to show how to read and parse CSV content from an URL using Apache Commons CSV library.

Add Apache Commons CSV library to your Java project

To use Apache Commons CSV Java library in the Gradle build project, add the following dependency into the build.gradle file.

compile group: 'org.apache.commons', name: 'commons-csv', version: '1.8'

To use Apache Commons CSV Java library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.8</version>
</dependency>

To download the Apache Commons CSV jar file you can visit Apache Commons CSV download page at commons.apache.org

Read CSV from an URL using CSVParser.parse() method

For example we have a CSV file from a remote server that can be accessed via the URL https://simplesolution.dev/data/Customers.csv . In the following Java code example, we use CSVParser.parse() static method to create CSVParser object in order to read the CSV content from that URL.

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class ParseCsvFromURLExample {
    public static void main(String... args) throws MalformedURLException {
        URL url = new URL("https://simplesolution.dev/data/Customers.csv");

        CSVFormat csvFormat = CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase();

        try(CSVParser csvParser = CSVParser.parse(url, StandardCharsets.UTF_8, csvFormat)) {
            for(CSVRecord csvRecord : csvParser) {
                String firstName = csvRecord.get("First Name");
                String lastName = csvRecord.get("Last Name");
                String email = csvRecord.get("Email");
                String phoneNumber = csvRecord.get("Phone Number");

                System.out.println(firstName + "," + lastName + "," + email + "," + phoneNumber);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
John,Doe,john@simplesolution.dev,123-456-789
Emerson,Wilks,emerson@simplesolution.dev,123-456-788
Wade,Savage,wade@simplesolution.dev,123-456-787
Star,Lott,star@simplesolution.dev,123-456-786
Claudia,James,claudia@simplesolution.dev,123-456-785

Happy Coding 😊

Read and Parse CSV Content from a String in Java using Apache Commons CSV

Write and Read CSV File in Java using Apache Commons CSV

Top 3 Libraries for Writing and Reading CSV File in Java

Spring Boot Web Application Download CSV File

Escape or Unescape String for CSV column data in Java using Apache Commons Text