Monday, 5 October 2015

Java: write to csv file

By using CSVPrinter class we can write csv data to a file.

Step 1: Create Filewriter object.
File file = new File(fileName);
FileWriter writer = new FileWriter(file);

Step 2: Initialize CSVFormat instance.
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");

Step 3: Initialize CSVPrinter instance. CSVPrinter is used to print values in csv format.
CSVPrinter csvFilePrinter = new CSVPrinter(writer, csvFileFormat);

Step 4: Write data to file, using ‘printRecord’ (or) printRecords’ method of CSVPrinter class.
csvFilePrinter.printRecords(values);
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);

	}
}

Run the application Test.java, you can see records are written to log.csv file.

$ cat log.csv
id,firstName,lastName,designation
1,Hari Krishna,Gurram,Software Developer
2,Kiran Kumar,Darsi,Senior Software Developer
3,Rama Krishna,Gurram,Software Developer
4,Gopi,Battu,Team lead
5,Sudheer,Ganji,Senior Software Developer



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment