Write or read a CSV file
1. POJO to map the CSV File:
First We need to create a POJO to have student data like id, name and age.
Student.java:
package com.learn;
public class Student {
private long id;
private String name;
private int age;
public Student(long id, String name,int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setFirstName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2. Write to CSV File:
We need to useCsvFileWriter to create a CSV (comma separated value format) file from a set of students data and save it in the specified directory.
Firstly, it writes the CSV file header, and then it writes the students data using FileWriter class.
CsvFileWriter.java:
package com.learn;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CsvFileWriter {
private static final String COMMA_DELIMITER = ",";
private static final String NEW_LINE_SEPARATOR = "\n";
//csv file header
private static final String FILE_HEADER = "id,name,age";
public static void writeToCsvFile(String fileName) {
//Create new students objects or get it from DB
Student student1 = new Student(1, "bala", 23);
Student student2 = new Student(2, "venkat", 26);
Student student3 = new Student(3, "sair", 24);
Student student4 = new Student(4, "harsha", 20);
Student student5 = new Student(5, "deva", 27);
Student student6 = new Student(6, "vel", 21);
//Create a new list of student objects
List students = new ArrayList();
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
students.add(student5);
students.add(student6);
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(fileName);
//Write the CSV file header
fileWriter.append(FILE_HEADER.toString());
//Add a new line separator after the header
fileWriter.append(NEW_LINE_SEPARATOR);
//Write a new student object list to the CSV file
for (Student student : students) {
fileWriter.append(String.valueOf(student.getId()));
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(student.getName());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(String.valueOf(student.getAge()));
fileWriter.append(NEW_LINE_SEPARATOR);
}
System.out.println("Data writed to CSV file!!!");
} catch (Exception e) {
System.out.println("Error in CsvFileWriter !!!");
e.printStackTrace();
}
}
}
3. Read from CSV File:
CsvFileReader class is used to read the CSV file in java using BufferedReader class then skipping the header and starting from the second line,
we split each line using String.split() function. A String.split() function splits string around matches of the given regular expression.
Finally, we create a new list of student and print it.
CsvFileReader.java:
package com.learn;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CsvFileReader {
private static final String COMMA_DELIMITER = ",";
//Student attributes index
private static final int STUDENT_ID_IDX = 0;
private static final int STUDENT_NAME_IDX = 1;
private static final int STUDENT_AGE = 2;
public static void readCsvFile(String fileName) {
BufferedReader fileReader = null;
try {
//Create a new list of student to be filled by CSV file data
List students = new ArrayList();
String line = "";
//Create the file reader
fileReader = new BufferedReader(new FileReader(fileName));
//Read the CSV file header to skip it
fileReader.readLine();
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(COMMA_DELIMITER);
if (tokens.length > 0) {
//Create a new student object and fill his data
Student student = newStudent(Long.parseLong(tokens[STUDENT_ID_IDX]), tokens[STUDENT_NAME_IDX], Integer.parseInt(tokens[STUDENT_AGE]));
students.add(student);
}
}
//Print the new student list
for (Student student : students) {
System.out.println(student.toString());
}
}
catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
}
}
}
1. POJO to map the CSV File:
First We need to create a POJO to have student data like id, name and age.
Student.java:
package com.learn;
public class Student {
private long id;
private String name;
private int age;
public Student(long id, String name,int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setFirstName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2. Write to CSV File:
We need to useCsvFileWriter to create a CSV (comma separated value format) file from a set of students data and save it in the specified directory.
Firstly, it writes the CSV file header, and then it writes the students data using FileWriter class.
CsvFileWriter.java:
package com.learn;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CsvFileWriter {
private static final String COMMA_DELIMITER = ",";
private static final String NEW_LINE_SEPARATOR = "\n";
//csv file header
private static final String FILE_HEADER = "id,name,age";
public static void writeToCsvFile(String fileName) {
//Create new students objects or get it from DB
Student student1 = new Student(1, "bala", 23);
Student student2 = new Student(2, "venkat", 26);
Student student3 = new Student(3, "sair", 24);
Student student4 = new Student(4, "harsha", 20);
Student student5 = new Student(5, "deva", 27);
Student student6 = new Student(6, "vel", 21);
//Create a new list of student objects
List students = new ArrayList();
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
students.add(student5);
students.add(student6);
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(fileName);
//Write the CSV file header
fileWriter.append(FILE_HEADER.toString());
//Add a new line separator after the header
fileWriter.append(NEW_LINE_SEPARATOR);
//Write a new student object list to the CSV file
for (Student student : students) {
fileWriter.append(String.valueOf(student.getId()));
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(student.getName());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(String.valueOf(student.getAge()));
fileWriter.append(NEW_LINE_SEPARATOR);
}
System.out.println("Data writed to CSV file!!!");
} catch (Exception e) {
System.out.println("Error in CsvFileWriter !!!");
e.printStackTrace();
}
}
}
3. Read from CSV File:
CsvFileReader class is used to read the CSV file in java using BufferedReader class then skipping the header and starting from the second line,
we split each line using String.split() function. A String.split() function splits string around matches of the given regular expression.
Finally, we create a new list of student and print it.
CsvFileReader.java:
package com.learn;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CsvFileReader {
private static final String COMMA_DELIMITER = ",";
//Student attributes index
private static final int STUDENT_ID_IDX = 0;
private static final int STUDENT_NAME_IDX = 1;
private static final int STUDENT_AGE = 2;
public static void readCsvFile(String fileName) {
BufferedReader fileReader = null;
try {
//Create a new list of student to be filled by CSV file data
List students = new ArrayList();
String line = "";
//Create the file reader
fileReader = new BufferedReader(new FileReader(fileName));
//Read the CSV file header to skip it
fileReader.readLine();
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(COMMA_DELIMITER);
if (tokens.length > 0) {
//Create a new student object and fill his data
Student student = newStudent(Long.parseLong(tokens[STUDENT_ID_IDX]), tokens[STUDENT_NAME_IDX], Integer.parseInt(tokens[STUDENT_AGE]));
students.add(student);
}
}
//Print the new student list
for (Student student : students) {
System.out.println(student.toString());
}
}
catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
}
}
}
No comments:
Post a Comment