com.github.timo_reymann.csv_parser.io.CsvWriter Maven / Gradle / Ivy
package com.github.timo_reymann.csv_parser.io;
import com.github.timo_reymann.csv_parser.meta.CsvMetaDataReader;
import com.github.timo_reymann.csv_parser.util.Converter;
import com.github.timo_reymann.csv_parser.util.Platform;
import lombok.Data;
import java.io.*;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
/**
* Write csv files
*
* @author Timo Reymann
* @since 20.12.17
*/
@Data
public class CsvWriter implements AutoCloseable, Closeable, Flushable {
/**
* Append to file instead of replacing it completely
*/
private final boolean append;
/**
* File has csv headers
*/
private final boolean hasHeadings;
/**
* Class for bean
*/
private Class clazz;
/**
* Meta data provider for bean
*/
private CsvMetaDataReader csvMetaDataReader;
/**
* File to save
*/
private File file;
/**
* Seperator for lines
*/
private String seperator = Seperator.SEMICOLON;
/**
* File writer instance
*/
private FileWriter fileWriter;
/**
* Buffered Writer to write to file
*/
private BufferedWriter bufferedWriter;
/**
* Converter api
*/
private final Converter converter = new Converter();
/**
* Create new csv writer
*
* @param clazz Class for bean
* @param file File to write
* @param append Append to output
* @param hasHeadings Has the file headings, if this is a new file headers are automatically generated
* @param seperator Seperator for csv file
* @throws IOException Error opening file streams
*/
public CsvWriter(Class clazz, File file, boolean append, boolean hasHeadings, String seperator) throws IOException {
this.clazz = clazz;
this.file = file;
this.csvMetaDataReader = new CsvMetaDataReader<>(clazz);
this.append = append;
this.hasHeadings = hasHeadings;
this.seperator = seperator;
init();
}
/**
* Map beans to string array, this method automatically decides to map by heading or by index
*
* @param bean Bean to map
* @return String array with bean data mapped
* @throws IllegalAccessException Error getting values from bean
* @throws IOException Error writing header
*/
private String[] map(T bean) throws IllegalAccessException, IOException {
if (hasHeadings) {
return mapByHeading(bean);
}
return mapByIndex(bean);
}
/**
* Map bean by index
*
* @param bean Bean
* @return String array with data mapped according to specification over annotations
* @throws IllegalAccessException Error getting values from bean
*/
private String[] mapByIndex(T bean) throws IllegalAccessException {
HashMap