http://opencsv.sourceforge.net/ JavaDoc http://opencsv.sourceforge.net/apidocs/index.html
Uninflected word
List<SampleBean> list = null;
//Read the file
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"))) {
CsvToBeanBuilder<SampleBean> builder = new CsvToBeanBuilder<SampleBean>(reader);
builder.withType(SampleBean.class);
list = builder.build().parse();
}
Description to add to builder
builder.withSeparator('\t');
Add @CsvBindByName
to the bean property. Specify by column name.
If there is no header line
public class SampleBean {
@CsvBindByName
private String col1 = null;
@CsvBindByName
private String col2 = null;
@CsvBindByName
private String col3 = null;
@CsvBindByName
private String col4 = null;
@CsvBindByName
private String col5 = null;
//Abbreviation
}
Add @CsvBindByPosition
to the bean property. Designation by column position.
If there is no header line
public class SampleBean {
@CsvBindByPosition(position = 0)
private String col1 = null;
@CsvBindByPosition(position = 1)
private String col2 = null;
@CsvBindByPosition(position = 2)
private String col3 = null;
@CsvBindByPosition(position = 3)
private String col4 = null;
@CsvBindByPosition(position = 4)
private String col5 = null;
//Abbreviation
}
Official site sample
Writer writer = new FileWriter("yourfile.csv");
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).build();
beanToCsv.write(beans);
writer.close();
The official sample method behaves as follows. -Header line is inserted, but all alphabetic characters are capitalized. -The output order of columns is ascending order of column names.
I thought that both could be controlled by using Strategy etc., but sometimes I had to create my own Strategy class. So, it seems easier to simply write using CSVWriter
.
Sample using CSVWriter
CSVWriterBuilder builder = new CSVWriterBuilder(writer);
builder.withSeparator('\t'); //Tab delimited
builder.withLineEnd("\r\n"); //Line feed code(By default\Become n)
try (ICSVWriter csvWriter = builder.build()) {
//header
csvWriter.writeNext(new String[] { "column1", "column2" }, false);
//Writing contents
for (SampleBean output : outputList) {
csvWriter.writeNext(new String[] { output.getColumn1(), output.getColumn2() }, false);
}
}
Recommended Posts