Java Program to Read Two Csv Files and Output to Csv
In an earlier article, I wrote about how to read and write CSV files in Java using Apache Commons CSV.
In this commodity, I'll take you through another open source library called OpenCSV for reading and writing CSV files in Java.
Calculation OpenCSV dependency
First of all, you need to add the OpenCSV dependency in your project. If you're a Maven user, add together the following dependency to your pom.xml
file.
<dependency > <groupId > com.opencsv </groupId > <artifactId > opencsv </artifactId > <version > 4.0 </version > </dependency >
And hither is the dependency for Gradle users -
compile "com.opencsv:opencsv:4.0"
Sample CSV file
Following are two sample CSV files that we'll read and parse in the examples presented in this commodity.
CSV file without a header - users.csv
Rajeev Kumar Singh ♥,rajeevs@instance.com,+91-9999999999,India Sachin Tendulkar,sachin@example.com,+91-9999999998,India Barak Obama,barak.obama@example.com,+1-1111111111,U.s. Donald Trump,donald.trump@example.com,+1-2222222222,United States
CSV file with a header - users-with-header.csv
proper name,email,telephone,land Rajeev Kumar Singh ♥,rajeevs@example.com,+91-9999999999,India Sachin Tendulkar,sachin@example.com,+91-9999999998,India Barak Obama,barak.obama@example.com,+ane-1111111111,United States Donald Trump,donald.trump@example.com,+1-2222222222,U.s.a.
Read a CSV file (Retrieve each record as a Cord assortment)
The instance beneath shows how to read and parse a CSV file using OpenCSV library. It reads the CSV records one past i into a String array -
import com.opencsv. CSVReader ; import coffee.io. IOException ; import java.io. Reader ; import java.nio.file. Files ; import java.nio.file. Paths ; public class OpenCSVReader { individual static final String SAMPLE_CSV_FILE_PATH = "./users.csv" ; public static void primary ( String [ ] args) throws IOException { effort ( Reader reader = Files . newBufferedReader ( Paths . get (SAMPLE_CSV_FILE_PATH) ) ; CSVReader csvReader = new CSVReader (reader) ; ) { // Reading Records 1 past One in a String assortment Cord [ ] nextRecord; while ( (nextRecord = csvReader. readNext ( ) ) != cypher ) { Arrangement .out. println ( "Name : " + nextRecord[ 0 ] ) ; Organisation .out. println ( "Email : " + nextRecord[ i ] ) ; System .out. println ( "Phone : " + nextRecord[ 2 ] ) ; System .out. println ( "Country : " + nextRecord[ 3 ] ) ; System .out. println ( "==========================" ) ; } } } }
Reading all records at once
In the higher up example, We read the CSV records ane by one using the readNext()
method. CSVReader
also provides a method called readAll()
to read all the records at once into a List<Cord[]>
.
// Reading All Records at in one case into a List<Cord[]> List < String [ ] > records = csvReader. readAll ( ) ; for ( String [ ] record : records) { System .out. println ( "Name : " + record [ 0 ] ) ; Organisation .out. println ( "Email : " + record [ 1 ] ) ; System .out. println ( "Phone : " + record [ 2 ] ) ; Organisation .out. println ( "Country : " + record [ 3 ] ) ; Organization .out. println ( "---------------------------" ) ; }
Annotation that, the higher up method loads the entire CSV contents into memory, and therefore is non suitable for large CSV files.
If you endeavor to read the Sample CSV file that contains a header, and then the header tape will as well be printed in the output. If you want to skip the header row, then you lot tin can use a CSVReaderBuilder
grade to construct a CSVReader
with the specified number of lines skipped.
import com.opencsv. CSVReaderBuilder ; CSVReader csvReader = new CSVReaderBuilder (reader) . withSkipLines ( i ) . build ( ) ;
Read a CSV file and parse the records into a Java Object
The real force of OpenCSV library is that y'all can directly parse CSV records into Java objects. There are ii ways of doing information technology - The offset method makes use of annotations and the second method uses Mapping strategies.
At that place are two types of annotations in OpenCSV - @CsvBindByName
and @CsvBindByPosition
. You tin employ these annotations to specify which CSV cavalcade should be bound to which member field of the Java object.
If the CSV file contains a header, then you tin utilize @CsvBindByName
notation to specify the mapping between the CSV columns and the fellow member fields.
The @CsvBindByName
notation accepts three parameters - cavalcade, required and locale. The required
and locale
parameters are optional, and you can omit the cavalcade
parameter equally well if the header name in the CSV file is same as the member field proper noun.
Hither is an example of a POJO form that makes use of @CsvBindByName
annotations -
import com.opencsv.bean. CsvBindByName ; public class CSVUser { @CsvBindByName private String name; @CsvBindByName (column = "email" , required = true ) private Cord email; @CsvBindByName (cavalcade = "phone" ) private Cord phoneNo; @CsvBindByName private String country; // Getters and Setters (Omitted for brevity) }
The example beneath shows how to read and parse the CSV records directly into your Java objects -
import com.opencsv.bean. CsvToBean ; import com.opencsv.bean. CsvToBeanBuilder ; import coffee.io. IOException ; import java.io. Reader ; import java.nio.file. Files ; import java.nio.file. Paths ; import coffee.util. Iterator ; import java.util. List ; public form OpenCSVReadAndParseToBean { individual static final String SAMPLE_CSV_FILE_PATH = "./users-with-header.csv" ; public static void main ( String [ ] args) throws IOException { attempt ( Reader reader = Files . newBufferedReader ( Paths . get (SAMPLE_CSV_FILE_PATH) ) ; ) { CsvToBean < CSVUser > csvToBean = new CsvToBeanBuilder (reader) . withType ( CSVUser . class ) . withIgnoreLeadingWhiteSpace ( true ) . build ( ) ; Iterator < CSVUser > csvUserIterator = csvToBean. iterator ( ) ; while (csvUserIterator. hasNext ( ) ) { CSVUser csvUser = csvUserIterator. next ( ) ; System .out. println ( "Name : " + csvUser. getName ( ) ) ; System .out. println ( "Electronic mail : " + csvUser. getEmail ( ) ) ; System .out. println ( "PhoneNo : " + csvUser. getPhoneNo ( ) ) ; System .out. println ( "Country : " + csvUser. getCountry ( ) ) ; Organization .out. println ( "==========================" ) ; } } } }
In the to a higher place instance, we obtained an Iterator
from csvToBean
object, and then looped through this iterator to remember every object 1 by ane.
The CsvToBean
class too provides a parse()
method which parses the unabridged CSV file and loads all the objects at once into retentiveness. You tin can apply information technology like so -
// Reads all CSV contents into memory (Not suitable for large CSV files) List < CSVUser > csvUsers = csvToBean. parse ( ) ; for ( CSVUser csvUser: csvUsers) { System .out. println ( "Proper name : " + csvUser. getName ( ) ) ; System .out. println ( "Electronic mail : " + csvUser. getEmail ( ) ) ; Organization .out. println ( "PhoneNo : " + csvUser. getPhoneNo ( ) ) ; Organisation .out. println ( "Country : " + csvUser. getCountry ( ) ) ; System .out. println ( "==========================" ) ; }
Apparently, the above method is not suitable for significantly big CSV files because it loads the entire CSV file contents into memory.
Using @CsvBindByPosition annotation
If your CSV file doesn't comprise a header, then y'all can use @CsvBindByPosition
annotation to specify the mappings similar this -
import com.opencsv.bean. CsvBindByPosition ; public form CSVUser { @CsvBindByPosition (position = 0 ) private String name; @CsvBindByPosition (position = i ) private String e-mail; @CsvBindByPosition (position = two ) private String phoneNo; @CsvBindByPosition (position = 3 ) individual Cord country; // Getters and Setters (Omitted for brevity) }
Read a CSV file and parse the records into a Java object without using annotations
If you don't want to clutter your POJO class with OpenCSV annotations, then you can use Mapping strategies to specify the mapping between CSV columns and object fellow member fields.
Consider the following MyUser
grade.
public class MyUser { private String name; private String electronic mail; private String phoneNo; private String country; public MyUser ( ) { } public MyUser ( String proper noun, String email, String phoneNo, String country) { this .name = name; this .email = email; this .phoneNo = phoneNo; this .land = land; } // Getters and Setters (Omitted for brevity) }
Hither is how you can use a ColumnPositionMappingStrategy
to specify the mapping between CSV columns and Java object'south member fields, and parse the CSV records into Java objects.
import com.opencsv.bean. ColumnPositionMappingStrategy ; import com.opencsv.bean. CsvToBean ; import com.opencsv.bean. CsvToBeanBuilder ; import java.io. IOException ; import java.io. Reader ; import java.nio.file. Files ; import java.nio.file. Paths ; import coffee.util. Iterator ; import java.util. List ; public form OpenCSVParseToBeanWithoutAnnotation { private static terminal String SAMPLE_CSV_FILE_PATH = "./users-with-header.csv" ; public static void principal ( Cord [ ] args) throws IOException { effort ( Reader reader = Files . newBufferedReader ( Paths . get (SAMPLE_CSV_FILE_PATH) ) ; ) { ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy ( ) ; strategy. setType ( MyUser . class ) ; String [ ] memberFieldsToBindTo = { "name" , "electronic mail" , "phoneNo" , "country" } ; strategy. setColumnMapping (memberFieldsToBindTo) ; CsvToBean < MyUser > csvToBean = new CsvToBeanBuilder (reader) . withMappingStrategy (strategy) . withSkipLines ( i ) . withIgnoreLeadingWhiteSpace ( true ) . build ( ) ; Iterator < MyUser > myUserIterator = csvToBean. iterator ( ) ; while (myUserIterator. hasNext ( ) ) { MyUser myUser = myUserIterator. next ( ) ; System .out. println ( "Name : " + myUser. getName ( ) ) ; System .out. println ( "Electronic mail : " + myUser. getEmail ( ) ) ; System .out. println ( "PhoneNo : " + myUser. getPhoneNo ( ) ) ; System .out. println ( "State : " + myUser. getCountry ( ) ) ; Organization .out. println ( "---------------------------" ) ; } } } }
The ColumnPositionMappingStrategy
is used to declare position based mapping. In the in a higher place example, nosotros accept bound the first column to proper noun
field, the second column to electronic mail
field and so on…
Generating a CSV file
You can generate a CSV file either from an array of Strings or from a List of objects.
Generate CSV file from Array of Strings
The example beneath shows how to generate a CSV file by writing an Assortment of Strings into each row of the CSV file.
import com.opencsv. CSVWriter ; import java.io. Writer ; import java.nio.file. Files ; import java.nio.file. Paths ; import java.io. IOException ; public grade OpenCSVWriter { private static final String STRING_ARRAY_SAMPLE = "./string-array-sample.csv" ; public static void chief ( String [ ] args) throws IOException { try ( Writer writer = Files . newBufferedWriter ( Paths . go (STRING_ARRAY_SAMPLE) ) ; CSVWriter csvWriter = new CSVWriter (writer, CSVWriter .DEFAULT_SEPARATOR, CSVWriter .NO_QUOTE_CHARACTER, CSVWriter .DEFAULT_ESCAPE_CHARACTER, CSVWriter .DEFAULT_LINE_END) ; ) { String [ ] headerRecord = { "Name" , "Email" , "Phone" , "Land" } ; csvWriter. writeNext (headerRecord) ; csvWriter. writeNext ( new String [ ] { "Sundar Pichai ♥" , "sundar.pichai@gmail.com" , "+1-1111111111" , "India" } ) ; csvWriter. writeNext ( new String [ ] { "Satya Nadella" , "satya.nadella@outlook.com" , "+1-1111111112" , "Republic of india" } ) ; } } }
Generate CSV file from List of Objects
Finally, following is an instance showing how to generate a CSV file from List of objects. The example uses the MyUser
form defined in the previous section -
import com.opencsv. CSVWriter ; import com.opencsv.bean. StatefulBeanToCsv ; import com.opencsv.bean. StatefulBeanToCsvBuilder ; import com.opencsv.exceptions. CsvDataTypeMismatchException ; import com.opencsv.exceptions. CsvRequiredFieldEmptyException ; import java.io. IOException ; import coffee.io. Writer ; import java.nio.file. Files ; import java.nio.file. Paths ; import java.util. ArrayList ; import java.util. List ; public class OpenCSVWriter { private static final String OBJECT_LIST_SAMPLE = "./object-list-sample.csv" ; public static void principal ( String [ ] args) throws IOException , CsvDataTypeMismatchException , CsvRequiredFieldEmptyException { attempt ( Author writer = Files . newBufferedWriter ( Paths . get (STRING_ARRAY_SAMPLE) ) ; ) { StatefulBeanToCsv < MyUser > beanToCsv = new StatefulBeanToCsvBuilder (writer) . withQuotechar ( CSVWriter .NO_QUOTE_CHARACTER) . build ( ) ; Listing < MyUser > myUsers = new ArrayList < > ( ) ; myUsers. add ( new MyUser ( "Sundar Pichai ♥" , "sundar.pichai@gmail.com" , "+1-1111111111" , "India" ) ) ; myUsers. add ( new MyUser ( "Satya Nadella" , "satya.nadella@outlook.com" , "+one-1111111112" , "Republic of india" ) ) ; beanToCsv. write (myUsers) ; } } }
Conclusion
That's all folks! In this article, We looked at different means of reading and writing CSV files in Java using OpenCSV library.
Yous tin find all the code samples presented in this article in my github repository. Consider giving the repository a star on github if you find it useful.
Thank you for reading. See you in the adjacent post.
Source: https://www.callicoder.com/java-read-write-csv-file-opencsv/
0 Response to "Java Program to Read Two Csv Files and Output to Csv"
Post a Comment