You should not reinvent the wheel and use a common csv parser library. For example you can just use Apache Commons CSV.

It will handle a lot of things for you and is much more readable. There is also OpenCSV, which is even more powerful and comes with annotations based mappings to data classes.

 try (Reader reader = Files.newBufferedReader(Paths.get("file.csv"));
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT
                    .withFirstRecordAsHeader()        
        ) {
            for (CSVRecord csvRecord : csvParser) {
                // Access
                String name = csvRecord.get("MyColumn");
                // (..)
          }

Edit: Anyway, if you really want to do it on your own, take a look at this example.

Answer from ixeption on Stack Overflow
🌐
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 - Parsing CSV files without relying on external libraries involves utilizing Java’s standard I/O and string manipulation capabilities. While this approach reduces dependencies, it requires careful handling of edge cases. Overview: Read the CSV file line by line using BufferedReader and split each line based on the comma delimiter. ... package org.example; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class CSVParserFileReaderBasic { /* Pros: No external dependencies.
Top answer
1 of 4
22

You should not reinvent the wheel and use a common csv parser library. For example you can just use Apache Commons CSV.

It will handle a lot of things for you and is much more readable. There is also OpenCSV, which is even more powerful and comes with annotations based mappings to data classes.

 try (Reader reader = Files.newBufferedReader(Paths.get("file.csv"));
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT
                    .withFirstRecordAsHeader()        
        ) {
            for (CSVRecord csvRecord : csvParser) {
                // Access
                String name = csvRecord.get("MyColumn");
                // (..)
          }

Edit: Anyway, if you really want to do it on your own, take a look at this example.

2 of 4
3

I managed to shorten your snippet a bit.

If I get you correctly, you need all values of a particular column. The name of that column is given.

The idea is the same, but I improved reading from the file (it reads once); removed code duplication (like line.split(",")), unnecessary wraps in List (Collectors.toList()).

// read lines once
List<String[]> lines = lines(path).map(l -> l.split(","))
                                  .collect(toList());

// find the title index
int titleIndex = lines.stream()
                      .findFirst()
                      .map(header -> asList(header).indexOf(titleToSearchFor))
                      .orElse(-1);

// collect needed values
return lines.stream()
            .skip(1)
            .map(row -> row[titleIndex])
            .collect(toList());

I've got 2 tips not related to the issue:

1. You have hardcoded a URI, it's better to move the value to a constant or add a method param.
2. You could move the main part out of the if clause if you checked the opposite condition !Files.exists(path) and threw an exception.

🌐
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
This code iterates through and outputs each map in the list, where each map corresponds to a CSV row, showing the mapping of column headers to their respective values. The expected output should demonstrate that each line from the CSV has been successfully converted into a Java Map<String, String>, accurately capturing the column headers and values:
🌐
GeeksforGeeks
geeksforgeeks.org › java › reading-csv-file-java-using-opencsv
Reading a CSV file in Java using OpenCSV - GeeksforGeeks
July 11, 2025 - The following example shows how to read data of CSV file separated by a semi-colon character. ... name;rollno;department;result;cgpa amar;42;cse;pass;8.6 rohini;21;ece;fail;3.2 aman;23;cse;pass;8.9 rahul;45;ee;fail;4.6 pratik;65;cse;pass;7.2 raunak;23;me;pass;9.1 suvam;68;me;pass;8.2 · For Custom separator first CSVParser with specific parser character is created.
🌐
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. Just do whatever you wants to do with them, if you are creating object, as shown in first example, then create them, otherwise you can simply print them like in second example. You can even use new Java 7 and Java 8 feature to read file more efficiently.
🌐
Apache Commons
commons.apache.org › proper › commons-csv › jacoco › org.apache.commons.csv › CSVParser.java.html
CSVParser.java - Apache Commons
If you have already parsed records ... consume a lot of system resources depending on the input. For example, if you're * parsing a 150MB file of CSV data the contents will be read completely into memory.</li> * </ol> * * <h2>Notes</h2> * <p> * The internal parser state is completely ...
🌐
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 - However, it’s common to see semicolon ... a CSV file into a Java object directly. 3.1 This example read a CSV file and map it to a Country object via the @CsvBindByPosition....
🌐
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 - In Java, there are different ways of reading and parsing CSV files. Let's discuss some of the best approaches such as OpenCSV, Super CSV etc.
Find elsewhere
Top answer
1 of 4
9

Side-effects

Stream.forEach() operation should be utilized with care since it operates via side-effects and should not be used as a substitution of a proper reduction operation.

The way you've written this stream is discouraged by the Stream API documentation because it makes code more cluttered and difficult to follow and more importantly your solution is broken with parallel streams (there should be no assumptions on the nature of the stream in your code).

In this particular case, you should be using Stream.toArray() operation instead.

Multiline lambdas

Try to void them. They bear a lot of cognitive load. If a lambda expression requires several lines or when you have a complex single-line lambda (e.g. with a nested stream in it), consider introducing a method.

Exceptions

In short, the purpose of exceptions is to indicate cases when it's not possible to proceed with the normal execution flow.

If you stumbled on a corrupt piece of data which violates invariant that are important for your business logic, usually you don't want to proceed processing it. That's a valid case to throw. You asked can you "throw from a stream"? Sure, it's just a means iteration.

I've seen some bickering over whether it's appropriate to use exceptions for the purpose of validation. Sure it is, we do employ Exceptions for Validation for decades.

Unless you're using exceptions to avoid conditional logic, or to make weird hacks like throwing in order to break from a recursive method, and you have a genuine invalid piece of data on your hands you can and should throw.

Another, important note: exceptions should be informative. If standard exception types can describe the case at hand, fine, if not introduce your own exception type.

Also, use proper exception messages that will be helpful in investigating the issue.

Static routines

Don't treat everything as util classes, use the Power of object-orientation to make more clean, cohesive and testable.

Refactored version

public class ArrayParser {
    private final String separator;
    private final int columnCount;
    
    public ArrayParser(String separator, int columnCount) {
        this.separator = separator;
        this.columnCount = columnCount;
    }
    
    public String[][] parse(final String str) {
        return str.lines()
            .map(this::parseLine)
            .toArray(String[][]::new);
    }
    
    private String[] parseLine(String toParse) {
        String[] line = toParse.split(separator);
        validateLine(line);
        return line;
    }
    
    private void validateLine(String[] line) {
        if (line.length != columnCount) {
            throw new LineParsingException(line, columnCount);
        }
    }
}

Exception example:

private class LineParsingException extends RuntimeException {
    private static final String MESSAGE_TEMPLATE = """
            The actual number of columns in the line
            %s
            doesn't match the expected number of columns %d""";
    
    public LineParsingException(String[] line, int columnsExpected) {
        super(MESSAGE_TEMPLATE.formatted(Arrays.toString(line), columnsExpected));
    }
}
2 of 4
7

conservative design

Since this is billed as "a CSV parser", a caller may reasonably believe they could send it any *.csv file produced by Excel. Better to advertise it as MyRestrictedCsvParser. The /** javadoc */ comments should explain the restrictions.

  1. Each field may or may not be enclosed in double quotes

This library should probably throw a fatal error upon encountering an ASCII 34 " double quote anywhere in an input line. Then a caller would not accidentally consume a data file in the belief that it had been parsed one way when in fact the library parsed it another way. That is, part of scoping down requirements is reducing the space of inputs you're willing to claim you successfully processed.

informative diagnostic

Throwing an unchecked exception within the JVM is great. It makes your library easier for callers to consume.

                throw new RuntimeException();

This is not a very diagnostic error. It needs two improvements:

  1. Subclass RuntimeException to create a library-specific error, perhaps CsvParseException.
  2. Mention the values of split.length and cols in the message, to save a maintenance engineer a little effort in diagnosing and repairing buggy inputs.

Consider keeping track of which line number we're on, so that can be included in the diagnostic message.

A caller should not be forced to catch a generic RuntimeException to recover from an error it knows how to deal with. We define new app-specific exception types to permit fine-grained catching. Lumping "wrong column count", "found a quote", and "zero lines" together would be acceptable, at least until you see how callers actually behave. If it turns out that callers really do wish to distinguish between those errors, then a v2 library release could always offer finer granularity on the error types.

signature

Clearly the OP code works. It seems slightly less convenient for the caller than it might be. There is redundant information encoded in the str and cols parameters.

Consider setting cols based on number of fields found in the first line of input.

Top answer
1 of 10
19

There is a serious problem with using

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

in order to parse CSV files, and that is because there can be commas within the data values, and in that case you must quote them, and ignore commas between quotes.

There is a very very simple way to parse this:

/**
* returns a row of values as a list
* returns null if you are past the end of the input stream
*/
public static List<String> parseLine(Reader r) throws Exception {
    int ch = r.read();
    while (ch == '\r') {
        //ignore linefeed chars wherever, particularly just before end of file
        ch = r.read();
    }
    if (ch<0) {
        return null;
    }
    Vector<String> store = new Vector<String>();
    StringBuffer curVal = new StringBuffer();
    boolean inquotes = false;
    boolean started = false;
    while (ch>=0) {
        if (inquotes) {
            started=true;
            if (ch == '\"') {
                inquotes = false;
            }
            else {
                curVal.append((char)ch);
            }
        }
        else {
            if (ch == '\"') {
                inquotes = true;
                if (started) {
                    // if this is the second quote in a value, add a quote
                    // this is for the double quote in the middle of a value
                    curVal.append('\"');
                }
            }
            else if (ch == ',') {
                store.add(curVal.toString());
                curVal = new StringBuffer();
                started = false;
            }
            else if (ch == '\r') {
                //ignore LF characters
            }
            else if (ch == '\n') {
                //end of a line, break out
                break;
            }
            else {
                curVal.append((char)ch);
            }
        }
        ch = r.read();
    }
    store.add(curVal.toString());
    return store;
}

There are many advantages to this approach. Note that each character is touched EXACTLY once. There is no reading ahead, pushing back in the buffer, etc. No searching ahead to the end of the line, and then copying the line before parsing. This parser works purely from the stream, and creates each string value once. It works on header lines, and data lines, you just deal with the returned list appropriate to that. You give it a reader, so the underlying stream has been converted to characters using any encoding you choose. The stream can come from any source: a file, a HTTP post, an HTTP get, and you parse the stream directly. This is a static method, so there is no object to create and configure, and when this returns, there is no memory being held.

You can find a full discussion of this code, and why this approach is preferred in my blog post on the subject: The Only Class You Need for CSV Files.

2 of 10
19

You also have the Apache Commons CSV library, maybe it does what you need. See the guide. Updated to Release 1.1 in 2014-11.

Also, for the foolproof edition, I think you'll need to code it yourself...through SimpleDateFormat you can choose your formats, and specify various types, if the Date isn't like any of your pre-thought types, it isn't a Date.

🌐
Medium
medium.com › @chathumalsangeeth › csv-file-parsing-made-easy-with-opencsv-in-java-c0b73fdf9ccf
CSV File Parsing Made Easy with OpenCSV in Java | by Chathumal Sangeeth | Medium
May 23, 2023 - import com.opencsv.bean.CsvToBeanBuilder; import model.CSV; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.List; public class A { public static void main(String[] args) throws FileNotFoundException { String fileName = System.getProperty("user.dir") + "\\src\\main\\resources\\data\\download.csv"; List<CSV> beans = new CsvToBeanBuilder(new FileReader(fileName)) .withType(CSV.class) .withSkipLines(1) // Used to skip 1st line.
🌐
Attacomsian
attacomsian.com › blog › java-read-parse-csv-file
How to read and parse a CSV file in Java
September 24, 2022 - In this article, we shall look at different ways to read and parse a CSV file in Java. Here is an example of a simple CSV file that uses a comma (,) as a delimiter to separate column values and doesn't contain any double-quote:
🌐
CodersLegacy
coderslegacy.com › home › learn java › java csv parser – apache commons
Java CSV Parser - Apache Commons - CodersLegacy
October 6, 2022 - This CSV parser was designed to ... Files in Java. As you’ll see further on, this Parser was designed with maximum compatibility with different formats and styles. In this article, we’ll cover both how to read and write to and from CSV Files, starting with reading. We’ll be using the following CSV File in the following examples...
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
Java CSV Parsing Example - Java Code Geeks
August 28, 2019 - In this article, I am demonstrating CSV file processing using Java. I will cover both reading from the CSV file and writing to the CSV file. The article is divided into different sections, ... This section lists the requirements to start the first CSV processing examples in Java.
🌐
GitHub
github.com › timo-reymann › csv-parser
GitHub - timo-reymann/csv-parser: Simple CSV-Parser for Java · GitHub
CsvReader<MyBean> reader = new CsvReader.Builder<MyBean>() .forClass(MyBean.class) // bean class object .file(new File("test.csv")) // specify file .inputStream(myInputStream) // or even stream .hasHeading() // file has headings .build(); // ...
Author   timo-reymann
🌐
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › org › apache › commons › csv › CSVParser.html
CSVParser (Apache Commons CSV 1.14.2-SNAPSHOT API)
Parses the CSV input according to the given format and returns the content as a list of CSVRecords. ... Gets the trailer comment, if any. ... Checks whether there is a header comment. ... Checks whether there is a trailer comment. ... Tests whether this parser is closed.
🌐
MojoAuth
mojoauth.com › parse-and-generate-formats › parse-and-generate-csv-with-java
Parse and Generate CSV with Java | Parse and Generate Formats
When parsing CSV files in Java, relying on a dedicated library like Apache Commons CSV is highly recommended. This approach sidesteps the complexities of manually handling edge cases such as fields enclosed in quotes that may contain embedded ...
🌐
Dukelearntoprogram
dukelearntoprogram.com › course2 › doc › javadoc › org › apache › commons › csv › CSVParser.html
CSVParser
For example if you're parsing a 150MB file of CSV data the contents will be read completely into memory. Internal parser state is completely covered by the format and the reader-state. ... If you do not read all records from the given reader, you should call close() on the parser, unless you ...
🌐
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. The first two examples show how to read a CSV file without a header, and the third example shows how to read a CSV file with a header.
🌐
Simplesolution
simplesolution.dev › java-read-and-parse-csv-file-using-apache-commons-csv
Read and Parse CSV File in Java using Apache Commons CSV
import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; public class ParseCsvFromPathExample { public static void main(String... args) { try { String csvFileName = "D:\\SimpleSolution\\Customers.csv"; CSVFormat csvFormat = CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase(); Path path = Paths.get(csvFileName); CSVParser csvParser = CSVParser.parse(path, StandardCharsets.UTF_8, csvFormat); f