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", ",");
Answer from DevilsHnd - 退した on Stack Overflow
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.

🌐
GeeksforGeeks
geeksforgeeks.org › java › reading-csv-file-java-using-opencsv
Reading a CSV file in Java using OpenCSV - GeeksforGeeks
July 11, 2025 - BeanToCsv - This class helps to export data to CSV file from your java application. ... For reading a CSV file you need CSVReader class.
Discussions

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 do you read data from a .csv file in Java?
Use a Scanner with delimiter set to ",". Or use a library like OpenCSV or SuperCSV. Source: http://stackoverflow.com/questions/14274259/java-read-csv-with-scanner , http://stackoverflow.com/questions/123/java-lib-or-app-to-convert-csv-to-xml-file . Also, Stack Overflow will always be your friend. More on reddit.com
🌐 r/learnprogramming
2
1
March 4, 2014
What are the different ways that you can parse and analyse CSV files in Java?
If you can read a file and split it by newlines and commas, that's really all you need to read/parse CSV. So you can definitely easily do this with Vanilla Java. More on reddit.com
🌐 r/learnprogramming
22
1
December 7, 2018
Trying to read data from a .csv file, not sure why sheet data is being returned as null.
Because it's not finding the file, that's what the error is telling you. Check if you find a file in the path that you mention. Also use a breakpoint to see where it fails. Use a try catch block and handle the exception. Google is your friend. More on reddit.com
🌐 r/learnjava
4
3
July 15, 2023
🌐
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 - Notably, we used the stream API to read the CSV file into a List<List<String>>. An important caveat to mention here is that readAllLines() puts everything in memory at once, so don’t use it to read large files.
🌐
TechVidvan
techvidvan.com › tutorials › read-csv-file-in-java
How to Read CSV file in Java - TechVidvan
July 1, 2020 - We use the CSVReader class to read a CSV file. The class CSVReader provides a constructor to parse a CSV file. ... 1: Create a class file with the name CSVReaderDemo and write the following code.
🌐
LabEx
labex.io › tutorials › java-reading-a-csv-file-117982
How to Read a CSV File in Java | LabEx
Reading CSV using BufferedReader Data read from CSV file: Row 0: name, age, city Row 1: John, 25, New York Row 2: Alice, 30, Los Angeles Row 3: Bob, 28, Chicago Row 4: Eve, 22, Boston · We import necessary Java classes for file I/O operations and data structures. We define the path to our CSV file (sample.csv).
🌐
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 ...
🌐
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();



        }




    }





}

}

Find elsewhere
🌐
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 - The RFC 4180 defines the format or definitions of a CSV file or text/csv file. 2.1 The OpenCSV is simple and easy to use CSV parser for Java.
🌐
Reddit
reddit.com › r/learnprogramming › how do you read data from a .csv file in java?
r/learnprogramming on Reddit: How do you read data from a .csv file in Java?
March 4, 2014 -

If I have an Excel file with columns of numerical values in and want to use these in a Java program how would I go about doing this?
In this case I have a few hundred rows of four-vectors (px, py, pz, E) and want to use the different values later on in the program (I can do this, it's just attempting to get the program to read them properly that's getting me stuck).

🌐
Medium
medium.com › tuanhdotnet › methods-and-techniques-for-working-with-csv-files-in-java-4601db73e08f
Methods and Techniques for Working with CSV Files in Java | by Anh Trần Tuấn | tuanhdotnet | Medium
July 19, 2025 - import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class CSVReaderExample { public static void main(String[] args) { String filePath = "data.csv"; // Replace with your CSV file path String line; String delimiter = ","; // Assumes a comma as the delimiter try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { while ((line = br.readLine()) != null) { String[] fields = line.split(delimiter); for (String field : fields) { System.out.print(field…
🌐
Scaler
scaler.com › home › topics › how to read csv file in java?
How to Read CSV File in Java?- Scaler Topics
January 13, 2024 - CSVReader - This class facilitates methods to read CSV files as a list of Array of Strings. CSVWriter - CSVWriter class is used to write to a CSV file with the help of a list of Array of Strings.
🌐
Vaadin
vaadin.com › blog › read-and-display-a-csv-file-in-java
Read and Display a CSV File in Java | Vaadin
March 7, 2022 - 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(); } } } To run the project from the command line, type mvnw spring-boot:run (on Windows), or ./mvnw spring-boot:run (on macOS or Linux).
🌐
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 - You open a CSV file and start reading it line by line, since each line contains a coma separated String, you need to split them using comma (",") and you will get an array of String containing each column.
🌐
How to do in Java
howtodoinjava.com › home › i/o › parse and read a csv file in java
Parse and Read a CSV File in Java
September 14, 2022 - We can use a separate Scanner to read lines, and another scanner to parse each line into tokens. This approach may not be useful for large files because it is creating one scanner instance per line. We can use the delimiter comma to parse the CSV file.
🌐
Attacomsian
attacomsian.com › blog › java-read-parse-csv-file
How to read and parse a CSV file in Java
September 24, 2022 - You can either use the BufferedReader class or the Scanner class to easily read the file in Java. Since CSV is just a plain-text file, the BufferedReader class can be used to read it line by line.
🌐
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 - ColumnPositionMappingStrategy: If you plan to use CsvToBean (or BeanToCsv) for importing CSV data, you will use this class to map CSV fields to java bean fields. As mentioned above, to read a CSV file we will take the help of CSVReader class.
🌐
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; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class RawJavaCSVReader { public static void main(String[] args) { String csvFile = "data.csv"; String line = ""; String csvDelimiter = ","; // CSV files typically use comma as delimiter List<String[]> data = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) { // Read the header line (first line) String headerLine = br.readLine(); if (headerLine != null) { String[] headers = headerLine.split(csvDelimiter); System.o
🌐
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,
🌐
e-iceblue
e-iceblue.com › Tutorials › Java › Spire.XLS-for-Java › Program-Guide › Document-Operation › read-csv-java.html
Read CSV Files in Java Efficiently: Step-by-Step Examples
Spire.XLS for Java provides the Workbook class to load CSV files and the Worksheet class to access data. Below are the steps to read CSV files line by line with automatic delimiter detection:
🌐
CodeSignal
codesignal.com › learn › courses › large-data-handling-techniques-in-java › lessons › reading-and-processing-csv-data-in-batches-with-java-1
Reading and Processing CSV Data in Batches with Java
We utilize CsvMapper and CsvSchema to map CSV records to Java objects. We read each CSV file and generate a MappingIterator to iterate through car records, leveraging the Car class to map each CSV row into a Java object.