[Java] Reading and writing files with OpenCSV

Official documentation

http://opencsv.sourceforge.net/ JavaDoc http://opencsv.sourceforge.net/apidocs/index.html

Make the read content a List of beans

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();
}

Read tab-delimited text

Description to add to builder


builder.withSeparator('\t');

If there is a header line

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

}

If there is no header line

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

}

Write to file

Write from a list of beans

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.

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

[Java] Reading and writing files with OpenCSV
[Review] Reading and writing files with java (JDK6)
Reading and writing Java basic files
Reading and writing gzip files in Java
[Java] Convert and import file values with OpenCSV
I tried to chew C # (reading and writing files)
[Java] Development with multiple files using package and import
Use java with MSYS and Cygwin
Distributed tracing with OpenCensus and Java
Install Java and Tomcat with Ansible
Use JDBC with Java and Scala.
Writing code with classes and instances
Output PDF and TIFF with Java 8
Drag and drop files with JavaFX
Encrypt with Java and decrypt with C #
Link Java and C ++ code with SWIG
Let's try WebSocket with Java and javascript!
[Java] Handle Excel files with Apache POI
[Java] How to output and write files!
Delete folders and files with File Manager
[Kotlin] Delete files with duplicate contents [Java]
Notes for reading and generating xlsx files from Java using Apache POI
[Java] What should I use for writing files?
Build and test Java + Gradle applications with Wercker
Try to link Ruby and Java with Dapr
Differences in writing Java, C # and Javascript classes
[Beginner] Upload images and files with Spring [Self-satisfaction]
Summarize the differences between C # and Java writing
Java and JavaScript
XXE and Java
Prepare a scraping environment with Docker and Java
Introduction to Apache Beam (1) ~ Reading and writing text ~
KMS) Envelope encryption with openssl and java decryption
Encrypt / decrypt with AES256 in PHP and Java
[Java] Get metadata from files with Apathce Tika, and get image / video width and height from metadata [Kotlin]
[Java] Align characters even with mixed half-width and full-width characters
Use fast Mapping library MapStruct with Lombok and Java 11
Solving with Ruby and Java AtCoder ABC129 D 2D array
Summary of ToString behavior with Java and Groovy annotations
Compile with Java 6 and test with Java 11 while running Maven on Java 8
Solving with Ruby, Perl and Java AtCoder ABC 128 C
[Java] Refer to and set private variables with reflection
Connect with port forwarding with SSH and send and receive files
I want to transition screens with kotlin and java!
Prepare the environment for java11 and javaFx with Ubuntu 18.4
Face recognition app made with Amazon Rekognition and Java
Serverless Java EE starting with Quarkus and Cloud Run
Install java with Homebrew
Getters and setters (Java)
Change seats with java
[Java] Thread and Runnable
Java true and false
[Java] String comparison and && and ||
Comfortable download with JAVA
Handle files with NIO.2.
Ruby Learning # 27 Writing Files
Switch java with direnv
Java --Serialization and Deserialization
[Java] Arguments and parameters
Download Java with Ansible
[Java] A technique for writing constructors, getters, and setters in one shot with IntelliJ IDEA.