🌐
Baeldung
baeldung.com › home › java › java io › introduction to opencsv
Introduction to OpenCSV | Baeldung
May 11, 2024 - In this quick tutorial, we’ll introduce OpenCSV 4, a fantastic library for writing, reading, serializing, deserializing, and/or parsing .csv files.
🌐
SourceForge
opencsv.sourceforge.net
opencsv –
Just beware that more threads and ... has for reading and writing CSV files involves defining beans that the fields of the CSV file can be mapped to and from, and annotating the fields of these beans so opencsv can do the rest....
🌐
GeeksforGeeks
geeksforgeeks.org › java › reading-csv-file-java-using-opencsv
Reading a CSV file in Java using OpenCSV - GeeksforGeeks
July 11, 2025 - 3. You can Download OpenCSV Jar and include in your project class path. ... CSVReader - This class provides the operations to read the CSV file as a list of String array.
🌐
SourceForge
opencsv.sourceforge.net › apidocs › com › opencsv › CSVReader.html
CSVReader (opencsv 5.12.0 API)
Returns if the CSVReader will verify the reader before each read. By default the value is true, which is the functionality for version 3.0. If set to false the reader is always assumed ready to read - this is the functionality for version 2.4 and before. The reason this method was needed was that certain types of readers would return false for their ready() methods until a read was done (namely readers created using Channels). This caused opencsv ...
🌐
ZetCode
zetcode.com › java › opencsv
Java Opencsv - read, write CSV files in Java with Opencsv
July 4, 2024 - Despite its name, CSV files can be separated with a delimiter other than a comma. The following example shows how to read numbers separated by a pipe | character. ... We have three rows of numbers separated with the | character. ... import com.opencsv.CSVParser; import com.opencsv.CSVParserBuilder; import com.opencsv.CSVReaderBuilder; import com.opencsv.exceptions.CsvException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; void main() throws IOException, CsvExceptio
🌐
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 - Now check the data.csv file. ID,FNAME,LNAME,COUNTRY,AGE 1,Lokesh,Gupta,India,32 2,David,Miller,England,34 3,Rahul,Vaidya,India,35 · OpenCSV also provides functionality to read CSV files to Java beans directly. Suppose the Java POJO is Employee class.
🌐
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 - Create a JAVA model to map CSV columns to read and parse. ... This is my sample data CSV file which I generated using the AutoTestData sample data generator. You also can generate a file with your choice of any data type.
🌐
DigitalOcean
digitalocean.com › community › tutorials › opencsv-csvreader-csvwriter-example
OpenCSV CSVReader CSVWriter Example | DigitalOcean
August 3, 2022 - CSVReader: This is the most important class in OpenCSV. CSVReader class is used to parse CSV files. We can parse CSV data line by line or read all data at once.
🌐
CalliCoder
callicoder.com › java-read-write-csv-file-opencsv
Read / Write CSV files in Java using OpenCSV | CalliCoder
February 18, 2022 - If you try to read the Sample CSV file that contains a header, then the header record will also be printed in the output. If you want to skip the header row, then you can use a CSVReaderBuilder class to construct a CSVReader with the specified number of lines skipped. import com.opencsv.CSVReaderBuilder; CSVReader csvReader = new CSVReaderBuilder(reader).withSkipLines(1).build();
Find elsewhere
🌐
Attacomsian
attacomsian.com › blog › read-write-csv-files-opencsv
How to read and write CSV files using OpenCSV
September 24, 2022 - A comprehensive guide to reading and writing CSV files using a popular open-source library OpenCSV in Java. Learn how to read CSV files as an array of strings or map CSV columns directly to Java objects.
🌐
Stack Abuse
stackabuse.com › reading-and-writing-csvs-in-java-with-opencsv
Reading and Writing CSVs in Java with OpenCSV
February 20, 2019 - The CSVReader is also implemented using Java Iterable, so it is possible to manage both memory and time constraints based on the implementation method you choose. OpenCSV has two objects types for reading CSVs - CSVReader, and its sub class CSVReaderHeaderAware.
🌐
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 - 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.
🌐
KSCodes
kscodes.com › home › how to read a simple csv file using opencsv
How to Read a Simple CSV File using OpenCSV - KSCodes
September 24, 2025 - Learn how to read CSV file in Java using OpenCSV. A simple guide with code examples to parse CSV files and display rows using CSVReader.
Top answer
1 of 2
17

CSVReader takes a Reader argument according to the documentation, so it isn't limited to a FileReader for the parameter.

To use a CSVReader without saving the file first, you could use a BufferedReader around a stream loading the data:

URL stockURL = new URL("http://example.com/stock.csv");
BufferedReader in = new BufferedReader(new InputStreamReader(stockURL.openStream()));
CSVReader reader = new CSVReader(in);
// use reader
2 of 2
0

Implementation of opencsv for reading csv file and saving to database.

import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.bean.CsvBindByPosition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.Column;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class FileUploadService {

    @Autowired
    private InsertCSVContentToDB csvContentToDB;


    /**
     * @param csvFileName location of the physical file.
     * @param type Employee.class
     * @param delimiter  can be , | # etc
     * @param obj    //new Employee();
     *
     *            import com.opencsv.bean.CsvBindByPosition;
     *            import lombok.Data;
     *
     *            import javax.persistence.Column;
     *
     *              @Data
     *              public class Employee {
     *
     *              @CsvBindByPosition(position = 0, required = true)
     *              @Column(name = "EMPLOYEE_NAME")
     *              private String employeeName;
     *
     *              @CsvBindByPosition(position = 1)
     *              @Column(name = "Employee_ADDRESS_1")
     *              private String employeeAddress1;
     *          }
     *
     * @param sqlQuery  query to save data to DB
     * @param noOfLineSkip make it 0(Zero) so that it should not skip any line.
     * @param auditId apart from regular column in csv we need to add more column for traking like file id or audit id
     * @return
     */
    public <T> void readCSVContentInArray(String csvFileName, Class<? extends T> type, char delimiter, Object obj,
                                                  String sqlQuery, int noOfLineSkip, Long auditId) {
        List<T> lstCsvContent = new ArrayList<>();
        Reader reader = null;
        CSVReader csv = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFileName), "utf-8"));
            log.info("Buffer Reader : " + ((BufferedReader) reader).readLine().isEmpty());
            CSVParser parser = new CSVParserBuilder().withSeparator(delimiter).withIgnoreQuotations(true).build();
            csv = new CSVReaderBuilder(reader).withSkipLines(noOfLineSkip).withCSVParser(parser).build();
            String[] nextLine;
            int size = 0;
            int chunkSize = 10000;
            Class params[] = { Long.class };
            Object paramsObj[] = { auditId };
            long rowNumber = 0;
            Field field[] = type.getDeclaredFields();
            while ((nextLine = csv.readNext()) != null) {
                rowNumber++;
                try {

                    obj = type.newInstance();

                    for (Field f : field) {
                        if(!f.isSynthetic()){
                            f.setAccessible(true);
                            Annotation ann[] = f.getDeclaredAnnotations();
                            CsvBindByPosition csv1 = (CsvBindByPosition) ann[0];
                            Column c = (Column)ann[1];

                            try {
                                if (csv1.position() < nextLine.length) {
                                    if (csv1.required() && (nextLine[csv1.position()] == null
                                            || nextLine[csv1.position()].trim().isEmpty())) {
                                        String message = "Mandatory field is missing in row: " + rowNumber;
                                        log.info("null value in " + rowNumber + ", " + csv1.position());
                                        System.out.println(message);

                                    }

                                    if (f.getType().equals(String.class)) {
                                        f.set(obj, nextLine[csv1.position()]);

                                    }
                                    if (f.getType().equals(Boolean.class)) {
                                        f.set(obj, nextLine[csv1.position()]);

                                    }
                                    if (f.getType().equals(Integer.class)) {
                                        f.set(obj, Integer.parseInt(nextLine[csv1.position()]));

                                    }
                                    if (f.getType().equals(Long.class)) {
                                        f.set(obj, Long.parseLong(nextLine[csv1.position()]));
                                    }
                                    if (f.getType().equals(Double.class) && null!=nextLine[csv1.position()] && !nextLine[csv1.position()].trim().isEmpty()  ) {
                                        f.set(obj, Double.parseDouble(nextLine[csv1.position()]));

                                    }if(f.getType().equals(Double.class) && ((nextLine[csv1.position()]==null) || nextLine[csv1.position()].isEmpty())){
                                        f.set(obj, new Double("0.0"));
                                    }
                                    if (f.getType().equals(Date.class)) {
                                        f.set(obj, nextLine[csv1.position()]);
                                    }
                                }
                            } catch (Exception fttEx) {
                                log.info("Exception when parsing the file: " + fttEx.getMessage());
                                System.out.println(fttEx.getMessage());
                            }
                        }
                    }
                    lstCsvContent.add((T) obj);
                    if (lstCsvContent.size() > chunkSize) {
                        size = size + lstCsvContent.size();
                        //write code to save to data base of file system in chunk.
                        lstCsvContent = null;
                        lstCsvContent = new ArrayList<>();
                    }

                } catch (Exception ex) {
                    log.info("Exception: " + ex.getMessage());
                }

            }
            //write code to save list into DB or file system
            System.out.println(lstCsvContent);
        } catch (Exception ex) {
            log.info("Exception:::::::: " + ex.getMessage());

        } finally {
            try {
                if (csv != null) {
                    csv.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ioe) {

                log.info("Exception when closing the file: " + ioe.getMessage());
            }
        }
        log.info("File Processed successfully: ");
    }


}
🌐
QA Automation Expert
qaautomation.expert › 2025 › 04 › 08 › mastering-csv-file-handling-in-java-with-opencsv
Mastering CSV File Handling in Java with OpenCSV – QA Automation Expert
April 8, 2025 - HOME Handling CSV files in Java is efficient with the OpenCSV library. It provides simple methods to read and write CSV files. Below is a detailed guide to mastering CSV file handling using OpenCSV: A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by…
🌐
Stack Overflow
stackoverflow.com › questions › 53288514 › read-a-csv-file-from-the-beginning-after-having-reached-the-end-java-opencsv
read a csv file from the beginning after having reached the end (Java, OpenCSV) - Stack Overflow
CopyList<String[]> records = csvReader.readAll(); int no_of_rows = records.size(); Copyimport com.opencsv.CSVReader; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Paths; public class CSV_Reader { private static final String SAMPLE_CSV_FILE_PATH = "some_path"; public static void main(String[] args) { try { Reader reader = Files.newBufferedReader(Paths.get(SAMPLE_CSV_FILE_PATH)); System.out.println("before new object"); CSVReader csvReader = new CSVReader(reader); String[] nextRecord; System.out.println("before while"); int no_of_rows = 0; while ( (nextRecord = csvReader.readNext()) != null ) { no_of_rows++; } System.out.println("Number of lines is: " + no_of_rows ); String[] string_vector = new String[no_of_rows]; while ((nextRecord = csvReader.readNext()) != null) { //I want to do some stuff here.
🌐
My Developer Journal
sunitc.dev › 2020 › 05 › 31 › read-csv-file-to-java-bean-using-open-csv
Read CSV File to Java Bean (using Open CSV) – My Developer Journal
April 22, 2021 - In this article we will look at how to read CSV files into Java objects. We will be using OpenCSV library to do the conversions, and look at some examples of how we can customize it based on requirement. 1. Pre-requisite In this article we will me use of Gradle to import the package dependencies…
🌐
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 com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import com.opencsv.exceptions.CsvException; import java.io.FileReader; import java.io.IOException; import java.util.List; public class OpenCSVReaderExample { public static void main(String[] args) { String csvFile = "data.csv"; try (CSVReader reader = new CSVReaderBuilder(new FileReader(csvFile)) .withSkipLines(0) // Skip lines if needed (e.g., skip header) .build()) { // Read all records at once List<String[]> allData = reader.readAll(); // Process each record for (int i = 0; i < allData.size(); i++) { String[] row = allData.get(i); if (i == 0) { System.out.println("Headers: " + String.join(", ", row)); } else { System.out.println("Row " + i + ": " + String.join(" | ", row)); } } System.out.println("Total records: " + allData.size()); } catch (IOException | CsvException e) { e.printStackTrace(); } } }