0% found this document useful (0 votes)
402 views8 pages

Super CSV Example

Example to read and write CSV file using SuperCSV. For this you need first you need to download supercsv jar file and add it to the build path.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
402 views8 pages

Super CSV Example

Example to read and write CSV file using SuperCSV. For this you need first you need to download supercsv jar file and add it to the build path.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

/*

* To change this license header, choose License Headers in Project Properties.


* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.core.supercsv;
/**
* This interface is responsible to give Person related operations.
* @author Hyderareefa
*/
public interface Customer {
public String getCustomerNo();
public void setCustomerNo(String customerNo);
public long getLoyaltyPoints();
public void setLoyaltyPoints(long loyaltyPoints);
public String getMailingAddress();
public void setMailingAddress(String mailingAddress);
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.core.supercsv;
import java.util.Date;
/**
* This class is responsible to to collect data from other Beans.
* @author Hyderareefa
*/
public class CustomerBean extends PersonBean implements Customer {
private String customerNo;
private long loyaltyPoints;
private String mailingAddress;
/**
* Constructor
*/
public CustomerBean() {
}
/**
* Constructor
* @param customerNo
* @param firstName
* @param lastName
* @param birthDate
* @param mailingAddress
* @param married
* @param numberOfKids
* @param favouriteQuote
* @param email
* @param loyaltyPoints
*/
public CustomerBean(final String customerNo, final String firstName, final S
tring lastName, final Date birthDate,
final String mailingAddress, final Boolean married, final Integer number
OfKids, final String favouriteQuote,
final String email, final long loyaltyPoints) {
super(firstName, lastName, birthDate, married, numberOfKids, favouriteQu
ote, email);
this.customerNo = customerNo;
this.loyaltyPoints = loyaltyPoints;
this.mailingAddress = mailingAddress;
}

@Override
public String getCustomerNo() {
return customerNo;
}
@Override
public long getLoyaltyPoints() {
return loyaltyPoints;
}
@Override
public String getMailingAddress() {
return mailingAddress;
}
@Override
public void setCustomerNo(String customerNo) {
this.customerNo = customerNo;
}
@Override
public void setLoyaltyPoints(long loyaltyPoints) {
this.loyaltyPoints = loyaltyPoints;
}

@Override
public void setMailingAddress(String mailingAddress) {
this.mailingAddress = mailingAddress;
}
@Override
public String toString() {
return String
.format(
"CustomerBean [customerNo=%s, firstName=%s, last
Name=%s, birthDate=%s, mailingAddress=%s, married=%s, numberOfKids=%s, favourite
Quote=%s, email=%s, loyaltyPoints=%s]",
customerNo, getFirstName(), getLastName(), getBi
rthDate(), mailingAddress, getMarried(),
getNumberOfKids(), getFavouriteQuote(), getEmail
(), loyaltyPoints);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.core.supercsv;
import java.io.FileReader;
import java.io.IOException;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.ParseBool;
import org.supercsv.cellprocessor.ParseDate;
import org.supercsv.cellprocessor.ParseInt;
import org.supercsv.cellprocessor.constraint.LMinMax;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.constraint.StrRegEx;
import org.supercsv.cellprocessor.constraint.UniqueHashCode;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.prefs.CsvPreference;
/**
*
* @author Hyderareefa
*/
public class Reading {

private final static String CSV_FILE_NAME = "E:/supercsv/writeWithCSVBeanWri
ter.csv";

public static void main(String[] args) throws Exception {
readWithCsvBeanReader();
}

/**
* This method set up the Cell Processor.
* @return processor
*/
private static CellProcessor[] getCellProcessors() {

/*
final String emailRegEX = "[a-z0-9\\\\._]+@[a-z0-9\\\\.]+";
StrRegEx.registerMessage(emailRegEX, "Must be a valid email address.");
*/

final CellProcessor[] processor = new CellProcessor[] {
new UniqueHashCode(), //customerNo
new NotNull(), // firstName
new NotNull(), // lastName
new ParseDate("dd/MM/yyyy"), // birthDate
new NotNull(), // mailingAddress
new Optional(new ParseBool()), // married
new Optional(new ParseInt()), // numberOfKids
new NotNull(), // favouriteQuote
new NotNull(), // email
new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints
};
return processor;
}

/**
* This method is responsible to read data from CSV file using CSVBeanReader
.
* @throws Exception
*/
public static void readWithCsvBeanReader() throws Exception {
ICsvBeanReader beanReader = null;
try {
beanReader = new CsvBeanReader(new FileReader(CSV_FILE_NAME),CsvPref
erence.STANDARD_PREFERENCE);
final String[] header = beanReader.getHeader(true);
final CellProcessor[] processor = getCellProcessors();
CustomerBean customer;
while((customer = beanReader.read(CustomerBean.class, header, proces
sor)) != null) {
System.out.println(String.format("Line no = %s, RowNo = %s, Cust
omer = %s",
beanReader.getLineNumber(), beanReader.getRowNumber(), c
ustomer));
}
} catch(IOException ie) {
System.out.println(ie.getMessage());
} finally {
try {
if(beanReader != null) {
beanReader.close();
}
} catch(IOException ie) {
System.out.println(ie.getMessage());
}
}
}



}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.core.supercsv;
/**
*
* @author Hyderareefa
*/
public class SampleTest {
public static void main(String[] args) {
new Test().getValue();
}
}
class Test {
boolean value;
public Test() {
value = true;
}
public void getValue() {
System.out.println(value);
initialize();
System.out.println(value);
}
public void initialize() {
value = false;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.core.supercsv;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.supercsv.cellprocessor.FmtBool;
import org.supercsv.cellprocessor.FmtDate;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.constraint.LMinMax;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.constraint.UniqueHashCode;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.CsvListWriter;
import org.supercsv.io.CsvMapWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.io.ICsvListWriter;
import org.supercsv.io.ICsvMapWriter;
import org.supercsv.prefs.CsvPreference;
/**
*
* @author Hyderareefa
*/
public class Writing {

public static void main(String[] args) throws Exception {
writeWithCSVBeanWriter();
writeWithCSVListWriter();
writeWithCSVMapWriter();
}


/**
* This method is responsible to generate an CellProcessor
* @return processors
*/
private static CellProcessor[] getCellProcessor() {
final CellProcessor[] processors = new CellProcessor[] {
new UniqueHashCode(), //customerNo (must be unique)
new NotNull(), //firstName
new NotNull(), //lastName
new FmtDate("dd/MM/yyyy"), //birthDate
new NotNull(), //mailingAddress
new Optional(new FmtBool("Y", "N")), //married
new Optional(), //numberofKids
new Optional(), //favouriteQuote
new NotNull(), //email
new LMinMax(0L, LMinMax.MAX_LONG) //loyalityPoints
};
return processors;
}


/**
* This method is responsible to write data into a CSV file
* using CSVBeanWriter.
*
* @throws Exception
*/
public static void writeWithCSVBeanWriter() throws Exception {
final CustomerBean john = new CustomerBean("1", "John", "Dunbar", new Gr
egorianCalendar(1945, Calendar.JUNE, 13).getTime(),
"1600 Amphitheater Parkway\nMountain View, CA 94043\nUnited Stat
es", null, null,
"\"May the Force be with you.\" - Star Wars", "[email protected]
m", 0L);
final CustomerBean bob = new CustomerBean("2", "Bob", "Down", new Gregor
ianCalendar(1919, Calendar.FEBRUARY, 25).getTime(),
"1601 Willow Rd.\nMenlo Park, CA 94056\nUnited States", Boolean.
TRUE, 0,
"\"Frankly, my dear I don't give a damn.\" - Gone With the Wind
", "bobdown@[email protected]", 123456L);

final List<CustomerBean> customers = Arrays.asList(john, bob);
ICsvBeanWriter beanWriter = null;
try {
beanWriter = new CsvBeanWriter(new FileWriter("E:/supercsv/writeWith
CSVBeanWriter.csv"), CsvPreference.STANDARD_PREFERENCE);
final String[] header = new String[] {"customerNo", "firstName", "la
stName", "birthDate", "mailingAddress", "married", "numberOfKids", "favouriteQuo
te", "email", "loyaltyPoints"};
final CellProcessor[] processors = getCellProcessor();
beanWriter.writeHeader(header);
for(final CustomerBean customer :customers) {
beanWriter.write(customer, header, processors);
}
} catch(IOException io) {
System.out.println(io.getMessage());
} finally {
try {
if(beanWriter != null) {
beanWriter.close();
}
} catch(IOException io) {
System.out.println(io.getMessage());
}
}
}

/**
* This method is responsible to write the data into CSV file
* using CSVListWriter.
* @throws Exception
*/
public static void writeWithCSVListWriter() throws Exception {
final List<Object> john = Arrays.asList(new Object[] {"1", "John", "Dunb
ar", new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(),
"1600 Amphitheater Parkway\nMountain View, CA 94043\nUnited Stat
es", null, null,
"\"May the Force be with you.\" - Star Wars", "[email protected]
m", 0L});
final List<Object> bob = Arrays.asList(new Object[] {"2", "Bob", "Down",
new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(),
"1601 Willow Rd.\nMenlo Park, CA 94056\nUnited States", Boolean.
TRUE, 0,
"\"Frankly, my dear I don't give a damn.\" - Gone With the Wind
", "bobdown@[email protected]", 123456L});
ICsvListWriter beanWriter = null;
try {
beanWriter = new CsvListWriter(new FileWriter("E:/supercsv/writeWith
ListCSVWriter.csv"), CsvPreference.STANDARD_PREFERENCE);
final CellProcessor[] processors = getCellProcessor();
final String[] header = new String[] {"customerNo", "firstName", "la
stName", "birthDate", "mailingAddress",
"married", "numberOfKids", "favouriteQuote", "email", "loyal
tyPoints"};
beanWriter.writeHeader(header);
beanWriter.write(john, processors);
beanWriter.write(bob, processors);
} catch(IOException io) {
System.out.println(io.getMessage());
} finally {
try {
if(beanWriter != null) {
beanWriter.close();
}
} catch(IOException io) {
System.out.println(io.getMessage());
}
}
}

/**
* This method is responsible for writing data into CSV file using
* CSVMapWriter
* @throws Exception
*/
public static void writeWithCSVMapWriter() throws Exception {
final String[] header = new String[] {"customerNo", "firstName", "lastNa
me", "birthDate", "mailingAddress",
"married", "numberOfKids", "favouriteQuote", "email", "loyal
tyPoints"};
final Map<String, Object> john = new HashMap<>();
john.put(header[0], "1");
john.put(header[1], "John");
john.put(header[2], "Dunbar");
john.put(header[3], new GregorianCalendar(1945, Calendar.JUNE, 13).getTi
me());
john.put(header[4], "1600 Amphitheatre Parkway\\nMountain View, CA 94043
\\nUnited States");
john.put(header[5], null);
john.put(header[6], null);
john.put(header[7], "\"May the Force be with you.\" - Star Wars");
john.put(header[8], "jdunbar@@gmail.com");
john.put(header[9], 0L);

final Map<String, Object> bob = new HashMap<>();
bob.put(header[0], "2");
bob.put(header[1], "Bob");
bob.put(header[2], "Down");
bob.put(header[3], new GregorianCalendar(1919, Calendar.FEBRUARY, 25).ge
tTime());
bob.put(header[4], "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States
");
bob.put(header[5], true);
bob.put(header[6], 0);
bob.put(header[7], "\"Frankly, my dear, I don't give a damn.\" - Gone Wi
th The Wind");
bob.put(header[8], "[email protected]");
bob.put(header[9], 123456L);

ICsvMapWriter mapWriter = null;
try {
mapWriter = new CsvMapWriter(new FileWriter("E:/supercsv/writeWithMa
pCSVWriter.csv"), CsvPreference.STANDARD_PREFERENCE);
final CellProcessor[] cellProcessors = getCellProcessor();
mapWriter.writeHeader(header);
mapWriter.write(john, header, cellProcessors);
mapWriter.write(bob, header, cellProcessors);
} catch(IOException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if(mapWriter != null) {
mapWriter.close();
}
} catch(IOException ex) {
System.out.println(ex.getMessage());
}
}
}


}

You might also like