You can use CSVReader

String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));
// if the first line is the header
String[] header = reader.readNext();
Answer from Parmod on Stack Overflow
🌐
Javatpoint
javatpoint.com › how-to-read-csv-file-in-java
Read CSV File in Java
How to Read CSV File in Java with oops, string, exceptions, multithreading, collections, jdbc, rmi, fundamentals, programs, swing, javafx, io streams, networking, sockets, classes, objects etc,
🌐
GeeksforGeeks
geeksforgeeks.org › java › reading-csv-file-java-using-opencsv
Reading a CSV file in Java using OpenCSV - GeeksforGeeks
July 11, 2025 - CSVReader csvReader = new CSVReaderBuilder(reader).withSkipLines(1).build(); ... // Java code to illustrate reading a // all data at once public static void readAllDataAtOnce(String file) { try { // Create an object of file reader // class with ...
People also ask

What is OpenCSV, and why should we use it for reading CSV files in Java?
OpenCSV is a Java library that provides a simple and efficient way to read and write CSV (Comma-Separated Values) files. It offers a user-friendly API for parsing CSV data, making it easier to work with tabular data in Java applications.
🌐
scaler.com
scaler.com › home › topics › how to read csv file in java?
How to Read CSV File in Java?- Scaler Topics
How can I handle header rows when reading a CSV file with OpenCSV?
OpenCSV provides a convenient option to handle header rows. You can use the `withHeader()` method to specify that the first row of the CSV file contains headers. Once enabled, you can use methods like `readNext()` or `readAll()` to access data using header names as keys.
🌐
scaler.com
scaler.com › home › topics › how to read csv file in java?
How to Read CSV File in Java?- Scaler Topics
How can I handle errors or exceptions when reading CSV files with OpenCSV?
OpenCSV provides error-handling mechanisms through exceptions like IOException and CsvValidationException. You can catch and handle these exceptions in your code to manage errors gracefully, such as handling file not found or invalid CSV format errors.
🌐
scaler.com
scaler.com › home › topics › how to read csv file in java?
How to Read CSV File in Java?- Scaler Topics
🌐
Java67
java67.com › 2019 › 05 › how-to-read-csv-file-in-java-using-jackson-library.html
How to Read or Parse CSV files with Header in Java using Jackson - Example Tutorial | Java67
It has both pros and cons but that's a topic for another day. Just remember that Jackson uses reflection hence a default no-argument constructor is mandatory in your class. Now, we'll write code to read this CSV file in Java and copy the objects into ArrayList or just print them into the console.
🌐
Mkyong
mkyong.com › home › java › how to read and parse csv file in java
How to read and parse CSV file in Java - Mkyong.com
December 26, 2020 - 3.2 If the CSV file containing header info, we also can use @CsvBindByName to map the CSV file to a Java object. ... start ip,end ip,country code, country "1.0.0.0","1.0.0.255","AU","Australia" "1.0.1.0","1.0.3.255","CN","China" "1.0.4.0","...
🌐
Coderanch
coderanch.com › t › 711047 › java › Read-header-CSV-file
Read the header of CSV file (Beginning Java forum at Coderanch)
June 12, 2019 - I would start by looking at different ways to read files. They are often better than trying to write your own CSV reading program. You can of course simply miss out the first line. Or read one line.If you change skip(...) to limit(...) in line 7, you can get only the header.
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › java io › reading a csv file into an array
Reading a CSV File into an Array | Baeldung
May 9, 2025 - You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence. Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time. ... Simply put, a CSV (Comma-Separated Values) file contains organized information separated by a comma delimiter. In this tutorial, we’ll look into different options to read a CSV file into a Java array.
🌐
Scaler
scaler.com › home › topics › how to read csv file in java?
How to Read CSV File in Java?- Scaler Topics
January 13, 2024 - Once enabled, you can use methods like readNext() or readAll() to access data using header names as keys. Q. How can I handle errors or exceptions when reading CSV files with OpenCSV?
Top answer
1 of 2
1

If your CSV file(s) always contains a Header Line which indicates the Table Column Names then it's just a matter of catching this line and splitting it so as to place those column names into a String Array (or collection, or whatever). The length of this array determines the amount of data expected to be available for each record data line. Once you have the Column Names it's gets relatively easy from there.

How you acquire your CSV file path and it's format type is obviously up to you but here is a general concept how to carry out the task at hand:

public static void readCsvToConsole(String csvFilePath, String csvDelimiter) {
    String line;                            // To hold each valid data line.
    String[] columnNames = new String[0];   // To hold Header names.
    int dataLineCount = 0;                  // Count the file lines.
    StringBuilder sb = new StringBuilder(); // Used to build the output String.
    String ls = System.lineSeparator();     // Use System Line Seperator for output.

    // 'Try With Resources' to auto-close the reader
    try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
        while ((line = br.readLine()) != null) {
            // Skip Blank Lines (if any).
            if (line.trim().equals("")) {
                continue;
            }
            dataLineCount++;
            // Deal with the Header Line. Line 1 in most CSV files is the Header Line.
            if (dataLineCount == 1) {
                /* The Regular Expression used in the String#split()
                   method handles any delimiter/spacing situation.*/
                columnNames = line.split("\\s{0,}" + csvDelimiter + "\\s{0,}");
                continue;   // Don't process this line anymore. Continue loop.
            }
            // Split the file data line into its respective columnar slot.
            String[] lineParts = line.split("\\s{0,}" + csvDelimiter + "\\s{0,}");
            /* Iterate through the Column Names and buld a String
               using the column names and its' respective data along
               with a line break after each Column/Data line.     */
            for (int i = 0; i < columnNames.length; i++) {
                sb.append(columnNames[i]).append(": ").append(lineParts[i]).append(ls);
            }
            // Display the data record in Console.
            System.out.println(sb.toString());  
            /* Clear the StringBuilder object to prepare for 
               a new string creation.     */
            sb.delete(0, sb.capacity());        
        }
    }
    // Trap these Exceptions
    catch (FileNotFoundException ex) {
        System.err.println(ex.getMessage());
    }
    catch (IOException ex) {
        System.err.println(ex.getMessage());
    }
}

With this method you can have 1 to thousands of columns, it doesn't matter (not that you would ever have thousands of data columns in any given record but hey....you never know... lol). And to use this method:

// Read CSV To Console Window.
readCsvToConsole("test.csv", ",");
2 of 2
0

Here is some code that I recently worked on for an interview that might help: https://github.com/KemarCodes/ms3_csv/blob/master/src/main/java/CSVProcess.java

If you always have 3 attributes, I would read the first line of the csv and set values in an object that has three fields: attribute1, attribute2, and attribute3. I would create another class to hold the three values and read all the lines after, creating a new instance each time and reading them in an array list. To print I would just print the values in the attribute class each time alongside each set of values.

🌐
Csvreader
csvreader.com › java_csv_samples.php
java code samples - CSV Reader
See code examples of how to use CsvReader to parse delimited files in Java.
🌐
Java67
java67.com › 2015 › 08 › how-to-load-data-from-csv-file-in-java.html
How to load data from CSV file in Java - Example | Java67
... You can load data from a CSV file in a Java program by using BufferedReader class from the java.io package. You can read the file line by line and convert each line into an object representing that data.
🌐
Thoughtcoders
thoughtcoders.com › blogs › how-to-read-csv-file-column-by-column-using-java
How To Read CSV File Column By Column Using Java
BHIVE Premium Whitefield Campus, Plot No. 77, JBR Tech Park, 6th Rd, Whitefield, EPIP Zone, Whitefield, Bengaluru, Karnataka 560066 · Email: info@thoughtcoders.com
🌐
Baeldung
baeldung.com › home › java › java io › reading csv headers into a list
Reading CSV Headers Into a List | Baeldung
May 27, 2024 - Learn how to read CSV headers into a list in Java using JDK classes, OpenCSV, and Apache Commons CSV. Explore these efficient methods with code examples for each approach.
🌐
Blogger
javarevisited.blogspot.com › 2015 › 06 › 2-ways-to-parse-csv-files-in-java-example.html
2 Ways to Parse CSV Files in Java - BufferedReader vs Apache Commons CSV Example
August 7, 2021 - In first method we read the file line by line and then split each line on comma to get a String array containing individual fields. We use this array to create Country object and add them into the List, which is returned by our method.
🌐
LabEx
labex.io › tutorials › java-reading-a-csv-file-117982
How to Read a CSV File in Java | LabEx
For each row, we print each field along with its corresponding header. The OpenCSV library handles the complex CSV formatting automatically, correctly parsing fields with commas enclosed in quotes. This makes it ideal for real-world CSV files that may contain complex data. OpenCSV offers several advantages over the basic approaches: It correctly handles quoted fields containing commas, newlines, and other special characters. It provides built-in support for reading into beans (Java objects).
🌐
CalliCoder
callicoder.com › java-read-write-csv-file-apache-commons-csv
Read / Write CSV files in Java using Apache Commons CSV | CalliCoder
February 18, 2022 - In this article, I’ll explain how to read and parse CSV files with a header and without a header using Apache Commons CSV.
🌐
CodeSignal
codesignal.com › learn › courses › parsing-table-data-in-java › lessons › parsing-csv-files-in-java-using-jackson-library
Parsing CSV Files in Java Using Jackson Library
List<Map<String, String>> will hold each row from the CSV file as a map, where the keys correspond to column headers. ... With the mapper and schema defined, we can now specify the CSV file, read its content, and parse it into structured data.
🌐
How to do in Java
howtodoinjava.com › home › java libraries › opencsv – read and write csv files in java
OpenCSV - Read and Write CSV Files in Java
October 1, 2022 - In the above method, the first argument is the ResultSet which we want to write to CSV file. And the second argument is boolean which represents whether we want to write header columns (table column names) to file or not. This tutorial explained the basic usage of the OpenCSV library to read and write CSV files from a Java application code.
🌐
javaspring
javaspring.net › blog › read-csv-java
Reading CSV Files in Java: A Comprehensive Guide — javaspring.net
When reading a CSV file with headers, you can use the headers to map the values to their corresponding columns. The simplest way to read a CSV file in Java is by using the BufferedReader class.
🌐
Quora
quora.com › Is-there-any-code-for-reading-a-CSV-file-in-Java
Is there any code for reading a CSV file in Java? - Quora
If CSV has headers, use header-aware APIs (Commons CSV or OpenCSV’s CSVToBean) to map rows to POJOs. Choose the approach that matches file complexity and production needs: quick scripts -> core Java; robust, maintainable code -> Commons CSV or Univocity.