Reading and Writing Objects From File in Java
In an earlier commodity, I wrote well-nigh how to read and write CSV files in Java using Apache Commons CSV.
In this article, I'll take you through another open source library called OpenCSV for reading and writing CSV files in Java.
Adding OpenCSV dependency
Get-go of all, you need to add the OpenCSV dependency in your project. If y'all're a Maven user, add together the post-obit dependency to your pom.xml
file.
<dependency > <groupId > com.opencsv </groupId > <artifactId > opencsv </artifactId > <version > iv.0 </version > </dependency >
And here is the dependency for Gradle users -
compile "com.opencsv:opencsv:four.0"
Sample CSV file
Following are ii sample CSV files that we'll read and parse in the examples presented in this article.
CSV file without a header - users.csv
Rajeev Kumar Singh ♥,rajeevs@example.com,+91-9999999999,India Sachin Tendulkar,sachin@example.com,+91-9999999998,Republic of india Barak Obama,barak.obama@example.com,+i-1111111111,U.s.a. Donald Trump,donald.trump@example.com,+1-2222222222,United states of america
CSV file with a header - users-with-header.csv
name,email,telephone,state Rajeev Kumar Singh ♥,rajeevs@example.com,+91-9999999999,Bharat Sachin Tendulkar,sachin@case.com,+91-9999999998,India Barak Obama,barak.obama@example.com,+1-1111111111,The states Donald Trump,donald.trump@example.com,+i-2222222222,United States
Read a CSV file (Retrieve each record as a String array)
The example below shows how to read and parse a CSV file using OpenCSV library. It reads the CSV records i by ane into a String array -
import com.opencsv. CSVReader ; import java.io. IOException ; import java.io. Reader ; import java.nio.file. Files ; import java.nio.file. Paths ; public grade OpenCSVReader { individual static terminal String SAMPLE_CSV_FILE_PATH = "./users.csv" ; public static void master ( String [ ] args) throws IOException { try ( Reader reader = Files . newBufferedReader ( Paths . get (SAMPLE_CSV_FILE_PATH) ) ; CSVReader csvReader = new CSVReader (reader) ; ) { // Reading Records 1 by One in a Cord array String [ ] nextRecord; while ( (nextRecord = csvReader. readNext ( ) ) != null ) { Arrangement .out. println ( "Proper noun : " + nextRecord[ 0 ] ) ; Organisation .out. println ( "Email : " + nextRecord[ ane ] ) ; Arrangement .out. println ( "Phone : " + nextRecord[ two ] ) ; System .out. println ( "Land : " + nextRecord[ 3 ] ) ; Arrangement .out. println ( "==========================" ) ; } } } }
Reading all records at once
In the above example, We read the CSV records ane past one using the readNext()
method. CSVReader
also provides a method called readAll()
to read all the records at once into a Listing<String[]>
.
// Reading All Records at once into a Listing<String[]> List < Cord [ ] > records = csvReader. readAll ( ) ; for ( String [ ] record : records) { Organization .out. println ( "Proper noun : " + record [ 0 ] ) ; System .out. println ( "Email : " + record [ 1 ] ) ; Organisation .out. println ( "Phone : " + record [ two ] ) ; Arrangement .out. println ( "State : " + tape [ 3 ] ) ; Arrangement .out. println ( "---------------------------" ) ; }
Note that, the above method loads the entire CSV contents into memory, and therefore is not suitable for large CSV files.
If you try to read the Sample CSV file that contains a header, then the header record will as well be printed in the output. If you want to skip the header row, and so you tin use a CSVReaderBuilder
course to construct a CSVReader
with the specified number of lines skipped.
import com.opencsv. CSVReaderBuilder ; CSVReader csvReader = new CSVReaderBuilder (reader) . withSkipLines ( 1 ) . build ( ) ;
Read a CSV file and parse the records into a Java Object
The real forcefulness of OpenCSV library is that you can direct parse CSV records into Coffee objects. There are ii ways of doing it - The first method makes utilize of annotations and the second method uses Mapping strategies.
There are 2 types of annotations in OpenCSV - @CsvBindByName
and @CsvBindByPosition
. You can use these annotations to specify which CSV column should be leap to which fellow member field of the Java object.
If the CSV file contains a header, so you lot can employ @CsvBindByName
annotation to specify the mapping between the CSV columns and the member fields.
The @CsvBindByName
annotation accepts iii parameters - column, required and locale. The required
and locale
parameters are optional, and yous can omit the column
parameter as well if the header proper name in the CSV file is same as the member field name.
Here is an example of a POJO form that makes use of @CsvBindByName
annotations -
import com.opencsv.bean. CsvBindByName ; public class CSVUser { @CsvBindByName private Cord name; @CsvBindByName (column = "email" , required = true ) individual String electronic mail; @CsvBindByName (column = "phone" ) private String phoneNo; @CsvBindByName private String country; // Getters and Setters (Omitted for brevity) }
The case below 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 java.io. IOException ; import java.io. Reader ; import java.nio.file. Files ; import java.nio.file. Paths ; import coffee.util. Iterator ; import java.util. Listing ; public class OpenCSVReadAndParseToBean { individual static final Cord SAMPLE_CSV_FILE_PATH = "./users-with-header.csv" ; public static void main ( String [ ] args) throws IOException { attempt ( Reader reader = Files . newBufferedReader ( Paths . become (SAMPLE_CSV_FILE_PATH) ) ; ) { CsvToBean < CSVUser > csvToBean = new CsvToBeanBuilder (reader) . withType ( CSVUser . grade ) . withIgnoreLeadingWhiteSpace ( truthful ) . build ( ) ; Iterator < CSVUser > csvUserIterator = csvToBean. iterator ( ) ; while (csvUserIterator. hasNext ( ) ) { CSVUser csvUser = csvUserIterator. next ( ) ; System .out. println ( "Name : " + csvUser. getName ( ) ) ; Arrangement .out. println ( "E-mail : " + csvUser. getEmail ( ) ) ; Arrangement .out. println ( "PhoneNo : " + csvUser. getPhoneNo ( ) ) ; System .out. println ( "Country : " + csvUser. getCountry ( ) ) ; System .out. println ( "==========================" ) ; } } } }
In the to a higher place instance, we obtained an Iterator
from csvToBean
object, and and then looped through this iterator to retrieve every object one by ane.
The CsvToBean
course also provides a parse()
method which parses the entire CSV file and loads all the objects at once into retentiveness. You tin can use 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 ( "Name : " + csvUser. getName ( ) ) ; System .out. println ( "Email : " + csvUser. getEmail ( ) ) ; System .out. println ( "PhoneNo : " + csvUser. getPhoneNo ( ) ) ; Organization .out. println ( "Land : " + csvUser. getCountry ( ) ) ; System .out. println ( "==========================" ) ; }
Plain, the above method is non suitable for significantly large CSV files considering information technology loads the entire CSV file contents into memory.
Using @CsvBindByPosition annotation
If your CSV file doesn't contain a header, then you tin can use @CsvBindByPosition
note to specify the mappings like this -
import com.opencsv.bean. CsvBindByPosition ; public class CSVUser { @CsvBindByPosition (position = 0 ) private String proper noun; @CsvBindByPosition (position = ane ) private Cord email; @CsvBindByPosition (position = ii ) individual String phoneNo; @CsvBindByPosition (position = 3 ) private Cord land; // Getters and Setters (Omitted for brevity) }
Read a CSV file and parse the records into a Coffee 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
form.
public class MyUser { private String name; private Cord e-mail; private String phoneNo; private Cord country; public MyUser ( ) { } public MyUser ( String proper noun, String email, Cord phoneNo, String state) { this .name = name; this .email = email; this .phoneNo = phoneNo; this .country = country; } // Getters and Setters (Omitted for brevity) }
Here is how you tin employ a ColumnPositionMappingStrategy
to specify the mapping between CSV columns and Coffee object's fellow member fields, and parse the CSV records into Java objects.
import com.opencsv.bean. ColumnPositionMappingStrategy ; import com.opencsv.edible bean. CsvToBean ; import com.opencsv.bean. CsvToBeanBuilder ; import java.io. IOException ; import java.io. Reader ; import coffee.nio.file. Files ; import java.nio.file. Paths ; import coffee.util. Iterator ; import java.util. List ; public class OpenCSVParseToBeanWithoutAnnotation { individual static terminal String SAMPLE_CSV_FILE_PATH = "./users-with-header.csv" ; public static void main ( Cord [ ] args) throws IOException { try ( Reader reader = Files . newBufferedReader ( Paths . get (SAMPLE_CSV_FILE_PATH) ) ; ) { ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy ( ) ; strategy. setType ( MyUser . form ) ; Cord [ ] memberFieldsToBindTo = { "name" , "email" , "phoneNo" , "country" } ; strategy. setColumnMapping (memberFieldsToBindTo) ; CsvToBean < MyUser > csvToBean = new CsvToBeanBuilder (reader) . withMappingStrategy (strategy) . withSkipLines ( 1 ) . withIgnoreLeadingWhiteSpace ( truthful ) . build ( ) ; Iterator < MyUser > myUserIterator = csvToBean. iterator ( ) ; while (myUserIterator. hasNext ( ) ) { MyUser myUser = myUserIterator. next ( ) ; System .out. println ( "Proper noun : " + myUser. getName ( ) ) ; System .out. println ( "E-mail : " + myUser. getEmail ( ) ) ; Organization .out. println ( "PhoneNo : " + myUser. getPhoneNo ( ) ) ; System .out. println ( "Country : " + myUser. getCountry ( ) ) ; System .out. println ( "---------------------------" ) ; } } } }
The ColumnPositionMappingStrategy
is used to declare position based mapping. In the above example, we have bound the offset column to proper name
field, the second cavalcade to email
field and 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 case below 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 coffee.io. Writer ; import java.nio.file. Files ; import java.nio.file. Paths ; import java.io. IOException ; public course OpenCSVWriter { individual static final String STRING_ARRAY_SAMPLE = "./string-array-sample.csv" ; public static void main ( String [ ] args) throws IOException { try ( Author author = Files . newBufferedWriter ( Paths . become (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" , "E-mail" , "Phone" , "Country" } ; csvWriter. writeNext (headerRecord) ; csvWriter. writeNext ( new String [ ] { "Sundar Pichai ♥" , "sundar.pichai@gmail.com" , "+1-1111111111" , "India" } ) ; csvWriter. writeNext ( new Cord [ ] { "Satya Nadella" , "satya.nadella@outlook.com" , "+1-1111111112" , "India" } ) ; } } }
Generate CSV file from List of Objects
Finally, post-obit is an case showing how to generate a CSV file from List of objects. The example uses the MyUser
course 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 java.io. Writer ; import java.nio.file. Files ; import java.nio.file. Paths ; import java.util. ArrayList ; import java.util. Listing ; public class OpenCSVWriter { private static last String OBJECT_LIST_SAMPLE = "./object-listing-sample.csv" ; public static void main ( String [ ] args) throws IOException , CsvDataTypeMismatchException , CsvRequiredFieldEmptyException { try ( Writer writer = Files . newBufferedWriter ( Paths . get (STRING_ARRAY_SAMPLE) ) ; ) { StatefulBeanToCsv < MyUser > beanToCsv = new StatefulBeanToCsvBuilder (author) . withQuotechar ( CSVWriter .NO_QUOTE_CHARACTER) . build ( ) ; Listing < MyUser > myUsers = new ArrayList < > ( ) ; myUsers. add ( new MyUser ( "Sundar Pichai ♥" , "sundar.pichai@gmail.com" , "+1-1111111111" , "Republic of india" ) ) ; myUsers. add ( new MyUser ( "Satya Nadella" , "satya.nadella@outlook.com" , "+1-1111111112" , "India" ) ) ; beanToCsv. write (myUsers) ; } } }
Decision
That's all folks! In this article, We looked at unlike ways of reading and writing CSV files in Java using OpenCSV library.
You can find all the code samples presented in this article in my github repository. Consider giving the repository a star on github if you observe information technology useful.
Thanks for reading. Meet y'all in the next post.
Source: https://www.callicoder.com/java-read-write-csv-file-opencsv/
0 Response to "Reading and Writing Objects From File in Java"
Post a Comment