Monday 5 October 2015

Java: Read csv file

In this post, I am going to show you how to read data from csv file.

Step 1: Initialize Reader instance.
Reader in = new FileReader(fileName);

Step 2: Get records from csv file.
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);

If your csv file has headers and you want to get fields by header name, initialize records like below.
records = CSVFormat.EXCEL.withHeader().parse(in);

Step 3: Use get method of CSVRecord to read a record field. CSVRecord class provides following methods to read fields by using name, index position.

public String get(final String name)
public String get(final int i)
Following is the complete working application.

public class Employee {

	private int id;
	private String firstName;
	private String lastName;
	private String designation;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public Employee(int id, String firstName, String lastName,
			String designation) {
		super();
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
		this.designation = designation;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Employee [id=").append(id).append(", firstName=")
				.append(firstName).append(", lastName=").append(lastName)
				.append(", designation=").append(designation).append("]");
		return builder.toString();
	}

}


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class EmployeeUtil {

	public static List<String> getCsv(Employee emp) {
		Objects.nonNull(emp);

		List<String> list = new ArrayList<>();

		list.add(emp.getId() + "");
		list.add(emp.getFirstName());
		list.add(emp.getLastName());
		list.add(emp.getDesignation());

		return list;
	}

	public static List<String> getHeader() {
		List<String> header = new ArrayList<>();

		header.add("id");
		header.add("firstName");
		header.add("lastName");
		header.add("designation");

		return header;

	}
}


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

public class CSVUtil {

	public static void writeToFile(String fileName, String recordSeparator,
			List<String> header, List<List<String>> values)
			throws FileNotFoundException, IOException {

		Objects.nonNull(fileName);
		Objects.nonNull(recordSeparator);

		File file = new File(fileName);
		FileWriter writer = new FileWriter(file);

		CSVFormat csvFileFormat = CSVFormat.DEFAULT
				.withRecordSeparator(recordSeparator);

		CSVPrinter csvFilePrinter = new CSVPrinter(writer, csvFileFormat);

		if (header != null)
			csvFilePrinter.printRecord(header);

		csvFilePrinter.printRecords(values);

		writer.flush();
		writer.close();
		csvFilePrinter.close();
	}

	public static List<String> readFromCSV(String fileName,
			String recordSeparator, List<String> headers) throws IOException {
		Objects.nonNull(fileName);

		List<String> result = new ArrayList<>();
		Reader in = new FileReader(fileName);
		Iterable<CSVRecord> records;

		if (headers == null) {
			records = CSVFormat.EXCEL.parse(in);
			for (CSVRecord record : records) {
				int size = record.size();
				StringBuilder builder = new StringBuilder();

				for (int i = 0; i < size; i++) {
					builder.append(record.get(i)).append(",");
				}
				String data = builder.toString();

				result.add(data.substring(0,
						(data.length() - recordSeparator.length())));
			}

		} else {
			records = CSVFormat.EXCEL.withHeader().parse(in);
			for (CSVRecord record : records) {
				StringBuilder builder = new StringBuilder();
				for (String header : headers) {
					builder.append(record.get(header)).append(",");
				}

				String data = builder.toString();

				result.add(data.substring(0,
						(data.length() - recordSeparator.length())));
			}
		}

		in.close();
		return result;
	}
}


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Test {
	public static void main(String args[]) throws FileNotFoundException,
			IOException {

		String fileName = "/Users/harikrishna_gurram/log.csv";

		File f = new File(fileName);
		f.getParentFile().mkdirs();
		f.createNewFile();

		Employee emp1 = new Employee(1, "Hari Krishna", "Gurram",
				"Software Developer");
		Employee emp2 = new Employee(2, "Kiran Kumar", "Darsi",
				"Senior Software Developer");
		Employee emp3 = new Employee(3, "Rama Krishna", "Gurram",
				"Software Developer");
		Employee emp4 = new Employee(4, "Gopi", "Battu", "Team lead");
		Employee emp5 = new Employee(5, "Sudheer", "Ganji",
				"Senior Software Developer");

		List<String> header = EmployeeUtil.getHeader();

		List<List<String>> employees = new ArrayList<>();
		employees.add(EmployeeUtil.getCsv(emp1));
		employees.add(EmployeeUtil.getCsv(emp2));
		employees.add(EmployeeUtil.getCsv(emp3));
		employees.add(EmployeeUtil.getCsv(emp4));
		employees.add(EmployeeUtil.getCsv(emp5));

		CSVUtil.writeToFile(fileName, "\n", header, employees);

		List<String> data = CSVUtil.readFromCSV(fileName, "\n", header);
		data.stream().forEach(System.out::println);

	}
}



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment