How to use OpenCSV bean to write to a File ?

OpenCSV is a popular open-source Java library that provides utilities for reading and writing CSV (Comma-Separated Values) files. It offers a simple and straightforward API for parsing CSV data and converting it into Java objects, as well as writing Java objects back to CSV format.

Here are some key features and functionalities of OpenCSV:

  1. CSV Parsing: OpenCSV allows you to read CSV files and convert each row into an array or a list of strings, making it easy to process and manipulate CSV data programmatically.
  2. Customizable Mapping: OpenCSV provides the ability to map CSV columns to specific fields or properties of Java objects. This allows you to directly convert CSV records into custom Java objects, simplifying the handling of CSV data.
  3. Support for Different CSV Formats: OpenCSV supports various CSV dialects, including different delimiter characters (e.g., comma, tab, semicolon) and quote characters. It can handle different line endings (e.g., CRLF, LF) and escape characters as well.
  4. CSV Writing: OpenCSV offers functionality for writing Java objects into CSV format. You can easily convert a collection of Java objects or arrays into CSV records and save them to a file or stream.
  5. Flexible Configuration: OpenCSV provides options to configure the CSV parsing and writing behavior, such as controlling how empty values, leading/trailing spaces, or quoted values are handled.
  6. Error Handling: OpenCSV provides mechanisms for handling exceptions and errors that may occur during CSV parsing or writing, allowing you to handle invalid or malformed CSV data gracefully.

OpenCSV is widely used in Java applications that require reading or writing CSV files, such as data import/export operations, data processing pipelines, and integration with systems that use CSV as a data interchange format.

Overall, OpenCSV simplifies the process of working with CSV data in Java, providing an easy-to-use and flexible API for parsing and writing CSV files. We do have whole lot of ways to write to a file. But this opencsv library is one of the new and spring friendly way. Feel free to use this in your project.

 protected static final char              DELIMITER        = '\'';
protected static final char              SEPARATOR        = ',';
protected static final String            EMPTY_STRING     = String.format("\\%s\\%s", DELIMITER,
    DELIMITER);
protected static final String            NULL             = "null";
protected static final DateTimeFormatter FILE_DATE_FORMAT = DateTimeFormatter
    .ofPattern("yyyy_MM_dd_HH_mm");    
/**
 * Configures writer with specified defaults
 * 
 * @param csvBuilder
 */
protected void configureWriter(StatefulBeanToCsvBuilder<?> csvBuilder)
{
    csvBuilder.withApplyQuotesToAll(true).withQuotechar(DELIMITER).withSeparator(SEPARATOR);
}
/**
 * Prepare StringWriter for output to file
 * 
 * @param <T>
 * @param bean
 * @return
 * @throws CsvDataTypeMismatchException
 * @throws CsvRequiredFieldEmptyException
 */
protected <T> StringWriter prepareWriter(List<T> bean)
    throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException
{
    StringWriter writer = new StringWriter();
    StatefulBeanToCsvBuilder<T> sbcBuilder = new StatefulBeanToCsvBuilder<>(writer);
    this.configureWriter(sbcBuilder);
    sbcBuilder.build().write(bean);
    return writer;
}
/**
 * Write your data to csv file
 * 
 * @param writer
 * @throws CsvDataTypeMismatchException
 * @throws CsvRequiredFieldEmptyException
 * @throws IOException
 */
protected void writeToFile(StringWriter writer, String folderLocation) throws IOException
{
    try (Writer fileWriter = fileWriter(folderLocation))
    {
        fileWriter.write(writer.toString().replaceAll(EMPTY_STRING, NULL));
        fileWriter.flush();
    }
}

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *