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
🌐
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.
Discussions

java - csv parser reading headers - Stack Overflow
I'm working on a csv parser, I want to read headers and the rest of the csv file separately. Here is my code to read csv. The current code reads everything in the csv file, but I need to read hea... More on stackoverflow.com
🌐 stackoverflow.com
How do I read a CSV File with JAVA - Stack Overflow
I have a probem, and I didnt find any solution yet. Following Problem: I have to read a CSV File which has to look like this: First Name,Second Name,Age, Lucas,Miller,17, Bob,Jefferson,55, Andrew, More on stackoverflow.com
🌐 stackoverflow.com
Reading CSV file.
You are using a relative path, so the jvm is looking at ${project dir}/Files/Crimes.csv. so if your project folder is called MyProject and located under C:/, then the jvm is looking for the file at C:/MyProject/Files/Crimes.csv. If the file is not there, you should use the absolute path. You can check exactly where you are telling the jvm the file is located by adding the following print statement. System.out.println(new File(file).getAbsolutePath()). For readability, change the variable name File to something else. You are using the actual File class, so having a variable name the same will only confuse you or others later. I would name it crimesFileName, that tells anybody reading it what exactly it is. Leaving it as File forces the reader to track back to where it is originally declared. More on reddit.com
🌐 r/learnjava
5
8
May 29, 2023
How to read csv file by using headers using java? - Stack Overflow
I have a csv file which contains 5 header fields like field1,field2,field3,field4,field5. The file contains data for this headers for different users. Some columns may contains null values as only ... More on stackoverflow.com
🌐 stackoverflow.com
January 15, 2014
🌐
Coderanch
coderanch.com › t › 711047 › java › Read-header-CSV-file
Read the header of CSV file (Beginning Java forum at Coderanch)
June 12, 2019 - If the first line contains row names (which I assume is what you're talking about), what is the difficulty in treating it as such when reading all the lines? If you're using a CSV library (which I recommend), that would probably have an option to treat the first row as a header. ... Yes I want to output all the rows from the file and the headers. But now just the rows are printed without header while(line=be.readline() !=null)...
🌐
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 ...
🌐
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 - CSVParser csvParser = new CSVParserBuilder().withSeparator(';').build(); // custom separator try(CSVReader reader = new CSVReaderBuilder( new FileReader(fileName)) .withCSVParser(csvParser) // custom CSV parser .withSkipLines(1) // skip the first line, header info .build()){ List<String[]> r = reader.readAll(); r.forEach(x -> System.out.println(Arrays.toString(x))); } Note The use of semicolon ; as the separator is not RFC 4180 compliant. However, it’s common to see semicolon separators in the CSV files; not everyone follows the RFC. The OpenCSV also support read or parse a CSV file into a Java object directly.
🌐
Baeldung
baeldung.com › home › java › java io › reading csv headers into a list
Reading CSV Headers Into a List | Baeldung
May 27, 2024 - Finally, we use the split() method alongside Arrays#asList to get the headers as a list. The Scanner class provides another solution to achieve the same outcome. As the name implies, it scans and reads the content of a given file. So, let’s add another test case to see how to use Scanner to read CSV file headers:
Top answer
1 of 4
8

We have withHeader() method available in CSVFormat. If you use this option then you will be able to read the file using headers.

CSVFormat format = CSVFormat.newFormat(',').withHeader();
Map<String, Integer> headerMap = dataCSVParser.getHeaderMap(); 

will give you all headers.

public class CSVFileReaderEx {
    public static void main(String[] args){
        readFile();
    }

    public static void readFile(){
         List<Map<String, String>> csvInputList = new CopyOnWriteArrayList<>();
         List<Map<String, Integer>> headerList = new CopyOnWriteArrayList<>();

         String fileName = "C:/test.csv";
         CSVFormat format = CSVFormat.newFormat(',').withHeader();

          try (BufferedReader inputReader = new BufferedReader(new FileReader(new File(fileName)));
                  CSVParser dataCSVParser = new CSVParser(inputReader, format); ) {

             List<CSVRecord> csvRecords = dataCSVParser.getRecords();

             Map<String, Integer> headerMap = dataCSVParser.getHeaderMap();
              headerList.add(headerMap);
              headerList.forEach(System.out::println);

             for(CSVRecord record : csvRecords){
                 Map<String, String> inputMap = new LinkedHashMap<>();

                 for(Map.Entry<String, Integer> header : headerMap.entrySet()){
                     inputMap.put(header.getKey(), record.get(header.getValue()));
                 }

                 if (!inputMap.isEmpty()) {
                     csvInputList.add(inputMap);
                } 
             }

             csvInputList.forEach(System.out::println);

          } catch (Exception e) {
             System.out.println(e);
          }
    }
}
2 of 4
6

Please consider the use of Commons CSV. This library is written according RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files. What is compatible to read such lines:

"aa,a","b""bb","ccc"

And the use is quite simple, there is just 3 classes, and a small sample according documentation:

Parsing of a csv-string having tabs as separators, '"' as an optional value encapsulator, and comments starting with '#':

 CSVFormat format = new CSVFormat('\t', '"', '#');
 Reader in = new StringReader("a\tb\nc\td");
 String[][] records = new CSVParser(in, format).getRecords();

And additionally you get this parsers already available as constants:

  • DEFAULT - Standard comma separated format as defined by RFC 4180.
  • EXCEL - Excel file format (using a comma as the value delimiter).
  • MYSQL - Default MySQL format used by the SELECT INTO OUTFILE and LOAD DATA INFILE operations. TDF - Tabulation delimited format.
Find elsewhere
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.

🌐
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).
🌐
DEV Community
dev.to › sadiul_hakim › comprehensive-csv-file-handling-in-java-tutorial-58fn
Comprehensive CSV File Handling in Java Tutorial - DEV Community
September 17, 2025 - import java.io.BufferedReader; ... BufferedReader(new FileReader(csvFile))) { // Read the header line (first line) String headerLine = br.readLine(); if (headerLine != null) { String[] headers = headerLine.split(csvDelimiter); ...
🌐
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?
🌐
javathinking
javathinking.com › blog › how-to-read-from-particular-header-in-opencsv
How to Read a Specific Header Column in CSV Files Using OpenCSV: A Step-by-Step Guide — javathinking.com
IDE: Any Java IDE (e.g., IntelliJ IDEA, Eclipse, or VS Code with Java extensions). Basic Java Knowledge: Familiarity with classes, methods, and exception handling. OpenCSV is a free, open-source library for parsing CSV files in Java.
🌐
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.
🌐
Reddit
reddit.com › r/learnjava › reading csv file.
r/learnjava on Reddit: Reading CSV file.
May 29, 2023 -
Ok im trying to read from a csv file and some how my directory can't find it can someone help. The Cvs file is in my project src file which I have named Files as well. 

Heres the code:


 import java.io.BufferedReader;

import java.io.FileReader; import java.io.IOException; import java.io.*; public class Operrations {

public static void main(String[] args) throws Exception {

    String File = "Files\\Crimes.csv";

    BufferedReader reader = null;

    String line = "";

    try {

        reader = new BufferedReader(new FileReader(File));

        while((line = reader.readLine()) !=null);

        String[] row = line.split(",");

        for(String index: row){

            System.out.printf("%-10", index);


        }

        System.out.println();






    




    }


    catch (Exception e){

        e.printStackTrace();



    }


    finally {


        try{


        reader.close();

        } catch(IOException e){

            e.printStackTrace();



        }




    }





}

}

🌐
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. Code of this method is very straight forward and self explanatory, we have ignored the first line because we know its header. Second method is interesting as it demonstrate how to use apache commons csv library to read csv file.
🌐
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,
🌐
CodeJava
codejava.net › coding › super-csv-reading-csv-files-into-pojos-with-csvbeanreader
Java Reading CSV File Example with Super CSV
package net.codejava.supercsv; import java.util.Date; public class Book { private String isbn; private String title; private String author; private String publisher; private Date published; private double price; public Book() { // this empty constructor is required } public Book(String isbn, String title, String author, String publisher, Date published, double price) { this.isbn = isbn; this.title = title; this.author = author; this.publisher = publisher; this.published = published; this.price = price; } // getters and setters }This POJO class defines fields that match the column headers in the CSV file. Remember to supply complete code for the getters and setters. Super CSV provides some classes called cell processors that automate data type conversions and enforce constraints when mapping values in the CSV file with JavaBean’s properties.
🌐
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.
🌐
Medium
medium.com › @zakariafarih142 › mastering-csv-parsing-in-java-comprehensive-methods-and-best-practices-a3b8d0514edf
Mastering CSV Parsing in Java: Comprehensive Methods and Best Practices | by Zakariafarih | Medium
November 25, 2024 - Simple CSV Files: For straightforward CSV files without embedded commas or quotes, basic file reading or the Scanner class suffices. Complex CSV Structures: When dealing with complex CSVs, external libraries like OpenCSV or Apache Commons CSV are recommended for their robustness. Performance and Scalability: Java Streams offer performance benefits for large files but may require additional handling for complex cases.