Simple CSV parsing example with POJO class.
Copy below classes to appropriate folders and run the class CsvParserExample.
Employee.java - com/csvparsing/pojo
CsvParserExample - com/csvparsing
ParseHelper - com/csvparsing/common
Employee POJO,
package com.csvparsing.pojo;
/**
* @author Sharoon
*
*/
public class Employee {
private int id;
private String name;
private String dob;
public Employee(int id, String name,String dob){
this.id = id;
this.name = name;
this.dob = dob;
}
public Employee() {
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the dob
*/
public String getDob() {
return dob;
}
/**
* @param string the dob to set
*/
public void setDob(String dob) {
this.dob = dob;
}
}
Main Class CsvParserExample,
package com.csvparsing;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.csvparsing.common.ParseHelper;
import com.csvparsing.pojo.Employee;
/**
*
* @author Sharoon
*
*/
public class CsvParserExample {
/**
* @param args
*/
public static void main(String[] args) {
// Reading employee List
List resultList = getEmployeeList();
formatAndDisplay(resultList);
// Insert a record into employee List
Employee newEmployee = new Employee();
newEmployee.setId(11);
newEmployee.setName("Vijay");
newEmployee.setDob("14/05/1985");
insertEmployeee(newEmployee);
}
private static void insertEmployeee(Employee newEmployee) {
try {
FileWriter pw = new FileWriter("src/com/csvparsing/employees.csv",true);
if(newEmployee !=null){
pw.append(String.valueOf(newEmployee.getId()));
pw.append(",");
pw.append(newEmployee.getName());
pw.append(",");
pw.append(newEmployee.getDob().toString());
pw.append("\n");
}
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Method to get the list of people by their name
* @param string
* @return
*/
public static List<Object> getEmployeeList() {
Employee employee = new Employee();
return processRecordsFromCSV("employees.csv", employee);
}
public static List<Object> processRecordsFromCSV(String fileName, Object record) {
List<Object> recordList = new ArrayList<Object>();
try{
String path = "src/com/csvparsing/"+fileName;
BufferedReader br = new BufferedReader( new FileReader(path));
String strLine = "";
String[] columns = ParseHelper.getColumns(br);
while((strLine = br.readLine()) != null){
Object newRecord = record.getClass().newInstance();
String[] values = strLine.split(",");
int size = values.length;
if(columns.length != size)
continue;
for(int i=0;i< size;i++){
String columnName = columns[i];
Field f1 = record.getClass().getDeclaredField(columnName);
f1.setAccessible(true);
f1.set(newRecord, getTypedValue(f1.getType(),values[i]));
}
recordList.add(newRecord);
}
br.close();
} catch(Exception e){
System.out.println("Exception occured while parsing CSV file : " + e);
}
return recordList;
}
/**
* Method to get typed value
* @param type
* @param value
* @return
*/
private static Object getTypedValue(Class<?> type, String value) {
Object typedValue = null;
if(type == int.class){
value = !"".equals(value)?value:"0";
typedValue = Integer.parseInt(value);
} else if(type == Date.class){
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
typedValue = (Date)(formatter.parse(value));
} catch (ParseException e) {
e.printStackTrace();
}
} else if(type == Double.class){
value = !"".equals(value)?value:"0.0";
typedValue = Double.parseDouble(value);
} else if(type == Float.class){
value = !"".equals(value)?value:"0.0f";
typedValue = Double.parseDouble(value);
} else if(type == boolean.class){
value = !"".equals(value)?value:"0.0f";
typedValue = Boolean.parseBoolean(value);
} else if(type == String.class){
typedValue = value;
}
return typedValue;
}
/**
*
* @param employeeList
*/
public static void formatAndDisplay(List<Employee> employeeList) {
System.out.println(" ## - Employee Records - ##");
System.out.println("Id \t"+"|"+"Name\t"+"|"+"|"+"DOB");
for(Employee employee:employeeList){
System.out.print(employee.getId()+"\t"+"|");
System.out.print(employee.getName()+"\t"+"|");
System.out.print(employee.getDob());
System.out.println();
}
}
}
ParseHelper Class to get Columns and its count.
package com.csvparsing.common;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* @author Sharoon
*
*/
public class ParseHelper {
public static int NO_OF_COLUMNS = 0;
public static String[] getColumns(BufferedReader br) {
String record = "";
StringTokenizer st = null;
String[] columns = null;
try {
if((record = br.readLine()) != null){
st = new StringTokenizer(record, ",");
columns = new String[st.countTokens()];
while(st.hasMoreTokens())
{
columns[NO_OF_COLUMNS] = st.nextToken();
NO_OF_COLUMNS++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return columns;
}
}
Csv File employee.csv

Copy below classes to appropriate folders and run the class CsvParserExample.
Employee.java - com/csvparsing/pojo
CsvParserExample - com/csvparsing
ParseHelper - com/csvparsing/common
employee.csv - com/csvparsing
Employee POJO,
package com.csvparsing.pojo;
/**
* @author Sharoon
*
*/
public class Employee {
private int id;
private String name;
private String dob;
public Employee(int id, String name,String dob){
this.id = id;
this.name = name;
this.dob = dob;
}
public Employee() {
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the dob
*/
public String getDob() {
return dob;
}
/**
* @param string the dob to set
*/
public void setDob(String dob) {
this.dob = dob;
}
}
Main Class CsvParserExample,
package com.csvparsing;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.csvparsing.common.ParseHelper;
import com.csvparsing.pojo.Employee;
/**
*
* @author Sharoon
*
*/
public class CsvParserExample {
/**
* @param args
*/
public static void main(String[] args) {
// Reading employee List
List resultList = getEmployeeList();
formatAndDisplay(resultList);
// Insert a record into employee List
Employee newEmployee = new Employee();
newEmployee.setId(11);
newEmployee.setName("Vijay");
newEmployee.setDob("14/05/1985");
insertEmployeee(newEmployee);
}
private static void insertEmployeee(Employee newEmployee) {
try {
FileWriter pw = new FileWriter("src/com/csvparsing/employees.csv",true);
if(newEmployee !=null){
pw.append(String.valueOf(newEmployee.getId()));
pw.append(",");
pw.append(newEmployee.getName());
pw.append(",");
pw.append(newEmployee.getDob().toString());
pw.append("\n");
}
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Method to get the list of people by their name
* @param string
* @return
*/
public static List<Object> getEmployeeList() {
Employee employee = new Employee();
return processRecordsFromCSV("employees.csv", employee);
}
public static List<Object> processRecordsFromCSV(String fileName, Object record) {
List<Object> recordList = new ArrayList<Object>();
try{
String path = "src/com/csvparsing/"+fileName;
BufferedReader br = new BufferedReader( new FileReader(path));
String strLine = "";
String[] columns = ParseHelper.getColumns(br);
while((strLine = br.readLine()) != null){
Object newRecord = record.getClass().newInstance();
String[] values = strLine.split(",");
int size = values.length;
if(columns.length != size)
continue;
for(int i=0;i< size;i++){
String columnName = columns[i];
Field f1 = record.getClass().getDeclaredField(columnName);
f1.setAccessible(true);
f1.set(newRecord, getTypedValue(f1.getType(),values[i]));
}
recordList.add(newRecord);
}
br.close();
} catch(Exception e){
System.out.println("Exception occured while parsing CSV file : " + e);
}
return recordList;
}
/**
* Method to get typed value
* @param type
* @param value
* @return
*/
private static Object getTypedValue(Class<?> type, String value) {
Object typedValue = null;
if(type == int.class){
value = !"".equals(value)?value:"0";
typedValue = Integer.parseInt(value);
} else if(type == Date.class){
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
typedValue = (Date)(formatter.parse(value));
} catch (ParseException e) {
e.printStackTrace();
}
} else if(type == Double.class){
value = !"".equals(value)?value:"0.0";
typedValue = Double.parseDouble(value);
} else if(type == Float.class){
value = !"".equals(value)?value:"0.0f";
typedValue = Double.parseDouble(value);
} else if(type == boolean.class){
value = !"".equals(value)?value:"0.0f";
typedValue = Boolean.parseBoolean(value);
} else if(type == String.class){
typedValue = value;
}
return typedValue;
}
/**
*
* @param employeeList
*/
public static void formatAndDisplay(List<Employee> employeeList) {
System.out.println(" ## - Employee Records - ##");
System.out.println("Id \t"+"|"+"Name\t"+"|"+"|"+"DOB");
for(Employee employee:employeeList){
System.out.print(employee.getId()+"\t"+"|");
System.out.print(employee.getName()+"\t"+"|");
System.out.print(employee.getDob());
System.out.println();
}
}
}
ParseHelper Class to get Columns and its count.
package com.csvparsing.common;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* @author Sharoon
*
*/
public class ParseHelper {
public static int NO_OF_COLUMNS = 0;
public static String[] getColumns(BufferedReader br) {
String record = "";
StringTokenizer st = null;
String[] columns = null;
try {
if((record = br.readLine()) != null){
st = new StringTokenizer(record, ",");
columns = new String[st.countTokens()];
while(st.hasMoreTokens())
{
columns[NO_OF_COLUMNS] = st.nextToken();
NO_OF_COLUMNS++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return columns;
}
}
Csv File employee.csv
No comments:
Post a Comment