Implement a Class Csvreader That Reads a Csv File, and Provide Methods
In an before article, I wrote well-nigh how to read and write CSV files in Java using Apache Commons CSV.
In this article, I'll accept you through some other open source library called OpenCSV for reading and writing CSV files in Java.
Adding OpenCSV dependency
First of all, you need to add the OpenCSV dependency in your project. If you're a Maven user, add together the post-obit dependency to your pom.xml file.
<dependency > <groupId > com.opencsv </groupId > <artifactId > opencsv </artifactId > <version > 4.0 </version > </dependency > And here is the dependency for Gradle users -
compile "com.opencsv:opencsv:4.0" Sample CSV file
Following are two sample CSV files that nosotros'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@case.com,+91-9999999998,India Barak Obama,barak.obama@instance.com,+ane-1111111111,Us Donald Trump,donald.trump@instance.com,+1-2222222222,United states of america CSV file with a header - users-with-header.csv
name,email,telephone,state Rajeev Kumar Singh ♥,rajeevs@case.com,+91-9999999999,India Sachin Tendulkar,sachin@example.com,+91-9999999998,India Barak Obama,barak.obama@instance.com,+i-1111111111,United States Donald Trump,donald.trump@case.com,+one-2222222222,United States Read a CSV file (Retrieve each record as a String array)
The instance below shows how to read and parse a CSV file using OpenCSV library. It reads the CSV records ane by one into a String array -
import com.opencsv. CSVReader ; import coffee.io. IOException ; import coffee.io. Reader ; import java.nio.file. Files ; import coffee.nio.file. Paths ; public course OpenCSVReader { individual static terminal String SAMPLE_CSV_FILE_PATH = "./users.csv" ; public static void main ( Cord [ ] args) throws IOException { try ( Reader reader = Files . newBufferedReader ( Paths . get (SAMPLE_CSV_FILE_PATH) ) ; CSVReader csvReader = new CSVReader (reader) ; ) { // Reading Records One by 1 in a String array String [ ] nextRecord; while ( (nextRecord = csvReader. readNext ( ) ) != null ) { System .out. println ( "Name : " + nextRecord[ 0 ] ) ; Organization .out. println ( "E-mail : " + nextRecord[ i ] ) ; System .out. println ( "Phone : " + nextRecord[ 2 ] ) ; System .out. println ( "Country : " + nextRecord[ 3 ] ) ; System .out. println ( "==========================" ) ; } } } } Reading all records at once
In the above instance, We read the CSV records one by one using the readNext() method. CSVReader also provides a method called readAll() to read all the records at one time into a List<String[]>.
// Reading All Records at once into a List<String[]> List < String [ ] > records = csvReader. readAll ( ) ; for ( String [ ] record : records) { System .out. println ( "Proper name : " + tape [ 0 ] ) ; System .out. println ( "Email : " + record [ i ] ) ; Organization .out. println ( "Telephone : " + tape [ two ] ) ; System .out. println ( "Land : " + record [ 3 ] ) ; System .out. println ( "---------------------------" ) ; } Notation that, the to a higher place method loads the entire CSV contents into memory, and therefore is non suitable for large CSV files.
If you lot attempt to read the Sample CSV file that contains a header, then the header record will also be printed in the output. If you lot want to skip the header row, then yous tin can utilise a CSVReaderBuilder class 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 Coffee Object
The real strength of OpenCSV library is that you can directly parse CSV records into Java objects. There are 2 ways of doing it - The first method makes use of annotations and the second method uses Mapping strategies.
There are two types of annotations in OpenCSV - @CsvBindByName and @CsvBindByPosition. You lot can use these annotations to specify which CSV column should be bound to which member field of the Java object.
If the CSV file contains a header, then you tin use @CsvBindByName annotation to specify the mapping betwixt 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 yous can omit the column parameter every bit well if the header name in the CSV file is same as the fellow member field proper noun.
Here is an example of a POJO class that makes utilise of @CsvBindByName annotations -
import com.opencsv.bean. CsvBindByName ; public class CSVUser { @CsvBindByName individual Cord name; @CsvBindByName (cavalcade = "electronic mail" , required = truthful ) individual Cord email; @CsvBindByName (column = "phone" ) private String phoneNo; @CsvBindByName private String land; // 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.edible bean. CsvToBean ; import com.opencsv.bean. CsvToBeanBuilder ; import java.io. IOException ; import coffee.io. Reader ; import java.nio.file. Files ; import java.nio.file. Paths ; import java.util. Iterator ; import java.util. List ; public course OpenCSVReadAndParseToBean { individual static concluding String SAMPLE_CSV_FILE_PATH = "./users-with-header.csv" ; public static void main ( String [ ] args) throws IOException { try ( Reader reader = Files . newBufferedReader ( Paths . get (SAMPLE_CSV_FILE_PATH) ) ; ) { CsvToBean < CSVUser > csvToBean = new CsvToBeanBuilder (reader) . withType ( CSVUser . course ) . withIgnoreLeadingWhiteSpace ( true ) . build ( ) ; Iterator < CSVUser > csvUserIterator = csvToBean. iterator ( ) ; while (csvUserIterator. hasNext ( ) ) { CSVUser csvUser = csvUserIterator. next ( ) ; System .out. println ( "Proper name : " + csvUser. getName ( ) ) ; Organisation .out. println ( "Email : " + csvUser. getEmail ( ) ) ; System .out. println ( "PhoneNo : " + csvUser. getPhoneNo ( ) ) ; System .out. println ( "Country : " + csvUser. getCountry ( ) ) ; System .out. println ( "==========================" ) ; } } } } In the in a higher place example, nosotros obtained an Iterator from csvToBean object, and then looped through this iterator to retrieve every object i by one.
The CsvToBean course besides provides a parse() method which parses the entire CSV file and loads all the objects at one time into retentivity. Yous tin can utilize it like so -
// Reads all CSV contents into retentiveness (Not suitable for large CSV files) Listing < CSVUser > csvUsers = csvToBean. parse ( ) ; for ( CSVUser csvUser: csvUsers) { System .out. println ( "Name : " + csvUser. getName ( ) ) ; System .out. println ( "E-mail : " + csvUser. getEmail ( ) ) ; System .out. println ( "PhoneNo : " + csvUser. getPhoneNo ( ) ) ; Organisation .out. println ( "Country : " + csvUser. getCountry ( ) ) ; System .out. println ( "==========================" ) ; } Obviously, the above method is not suitable for significantly large CSV files because it loads the entire CSV file contents into retentiveness.
Using @CsvBindByPosition note
If your CSV file doesn't contain a header, then you lot tin can use @CsvBindByPosition annotation to specify the mappings similar this -
import com.opencsv.bean. CsvBindByPosition ; public class CSVUser { @CsvBindByPosition (position = 0 ) private String name; @CsvBindByPosition (position = i ) private String email; @CsvBindByPosition (position = 2 ) private String phoneNo; @CsvBindByPosition (position = 3 ) private String country; // Getters and Setters (Omitted for brevity) } Read a CSV file and parse the records into a Java object without using annotations
If yous don't want to clutter your POJO course with OpenCSV annotations, and so you can utilize Mapping strategies to specify the mapping between CSV columns and object member fields.
Consider the post-obit MyUser form.
public form MyUser { individual String name; private String email; private String phoneNo; private String state; public MyUser ( ) { } public MyUser ( Cord name, Cord email, String phoneNo, String country) { this .proper name = proper name; this .email = email; this .phoneNo = phoneNo; this .country = country; } // Getters and Setters (Omitted for brevity) } Hither is how you tin 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.edible bean. ColumnPositionMappingStrategy ; import com.opencsv.bean. CsvToBean ; import com.opencsv.bean. CsvToBeanBuilder ; import coffee.io. IOException ; import java.io. Reader ; import java.nio.file. Files ; import coffee.nio.file. Paths ; import java.util. Iterator ; import java.util. List ; public course OpenCSVParseToBeanWithoutAnnotation { individual static terminal String SAMPLE_CSV_FILE_PATH = "./users-with-header.csv" ; public static void main ( String [ ] args) throws IOException { endeavour ( Reader reader = Files . newBufferedReader ( Paths . get (SAMPLE_CSV_FILE_PATH) ) ; ) { ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy ( ) ; strategy. setType ( MyUser . course ) ; String [ ] memberFieldsToBindTo = { "name" , "email" , "phoneNo" , "country" } ; strategy. setColumnMapping (memberFieldsToBindTo) ; CsvToBean < MyUser > csvToBean = new CsvToBeanBuilder (reader) . withMappingStrategy (strategy) . withSkipLines ( 1 ) . withIgnoreLeadingWhiteSpace ( true ) . build ( ) ; Iterator < MyUser > myUserIterator = csvToBean. iterator ( ) ; while (myUserIterator. hasNext ( ) ) { MyUser myUser = myUserIterator. next ( ) ; Arrangement .out. println ( "Name : " + myUser. getName ( ) ) ; System .out. println ( "Electronic mail : " + myUser. getEmail ( ) ) ; Arrangement .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, nosotros accept jump the outset column to name field, the second column to email field and and so on…
Generating a CSV file
You lot 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 instance 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 java.io. Writer ; import java.nio.file. Files ; import java.nio.file. Paths ; import coffee.io. IOException ; public course OpenCSVWriter { private static final String STRING_ARRAY_SAMPLE = "./cord-array-sample.csv" ; public static void principal ( String [ ] args) throws IOException { try ( Writer writer = 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" , "Electronic mail" , "Phone" , "Country" } ; csvWriter. writeNext (headerRecord) ; csvWriter. writeNext ( new String [ ] { "Sundar Pichai ♥" , "sundar.pichai@gmail.com" , "+ane-1111111111" , "India" } ) ; csvWriter. writeNext ( new Cord [ ] { "Satya Nadella" , "satya.nadella@outlook.com" , "+1-1111111112" , "India" } ) ; } } } Generate CSV file from List of Objects
Finally, following is an example showing how to generate a CSV file from Listing of objects. The instance uses the MyUser class divers 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 coffee.nio.file. Files ; import coffee.nio.file. Paths ; import coffee.util. ArrayList ; import java.util. Listing ; public class OpenCSVWriter { individual static concluding String OBJECT_LIST_SAMPLE = "./object-listing-sample.csv" ; public static void main ( String [ ] args) throws IOException , CsvDataTypeMismatchException , CsvRequiredFieldEmptyException { effort ( Writer writer = Files . newBufferedWriter ( Paths . go (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" , "Bharat" ) ) ; myUsers. add together ( new MyUser ( "Satya Nadella" , "satya.nadella@outlook.com" , "+1-1111111112" , "India" ) ) ; beanToCsv. write (myUsers) ; } } } Conclusion
That'southward all folks! In this article, We looked at dissimilar ways of reading and writing CSV files in Coffee using OpenCSV library.
You can find all the code samples presented in this commodity in my github repository. Consider giving the repository a star on github if you lot discover it useful.
Give thanks y'all for reading. Encounter you in the next mail.
Source: https://www.callicoder.com/java-read-write-csv-file-opencsv/
0 Response to "Implement a Class Csvreader That Reads a Csv File, and Provide Methods"
Post a Comment