Java, Spring, Spring Boot

How to use opencsv bean to write to a File ?

We do have whole lot of ways to write to a file. But this 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();
        }
    }

Leave a Reply