Read / Write CSV File With Apache Commons CSV

In this article, we will show you how to read/write CSV files using apache commons CSV which is an open-source free java library. This library makes the process simple and clear. You can focus on your business logic without care about the detailed file operation.

1. Download Apache Commons CSV Lib.

  1. Go to https://commons.apache.org/proper/commons-csv/download_csv.cgi.
  2. Click the download link of the latest version of the commons-csv library.
  3. After download the zip file, unzip it to a local folder.

2. Add commons-csv-1.4.jar In Your Java Project.

  1. Right-click your java project. Click “Properties—>Java Build Path—>Libraries
  2. Click the “Add External JARs” button to add common-csv-1.4.jar to the library.

3. DTO That Map To CSV File Row.

This DTO is used to store one row of data in the file.

public class UserAccountDTO {

	private int id;
	
	private String userName;
	
	private String password;
	
	private String email;
	
	private String age;
	
	private String mobile;

	public int getId() {
		return id;
	}

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

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public UserAccountDTO(int id, String userName, String password, String email, String age, String mobile) {
		super();
		this.id = id;
		this.userName = userName;
		this.password = password;
		this.email = email;
		this.age = age;
		this.mobile = mobile;
	}

	@Override
	public String toString() {
		StringBuffer retStrBuf = new StringBuffer();
		retStrBuf.append("id = " + this.id);
		retStrBuf.append(" , userName = " + this.userName);
		retStrBuf.append(" , password = " + this.password);
		retStrBuf.append(" , email = " + this.email);
		retStrBuf.append(" , age = " + this.age);
		retStrBuf.append(" , mobile = " + this.mobile);
		return retStrBuf.toString();
	}
	
	
}

4. Write Data To CSV File Method.

private void writeToCsv(String csvFilePath)
{
	System.out.println("Prepare file row data. ");
	/* Create 6 UserAccountDTO object, one oobject represent one line in the file. */
	UserAccountDTO userDto1 = new UserAccountDTO(1, "jack", "jack123456789", "[email protected]", "35", "12390973837");
	UserAccountDTO userDto2 = new UserAccountDTO(2, "jackie", "jackie123456789", "[email protected]", "38", "13901223456");
	UserAccountDTO userDto3 = new UserAccountDTO(3, "tom", "tom", "[email protected]", "30", "12390973837");
	UserAccountDTO userDto4 = new UserAccountDTO(4, "steven", "steven22222", "[email protected]", "37", "12390973837");
	UserAccountDTO userDto5 = new UserAccountDTO(5, "john", "john66366", "[email protected]", "50", "98979898576532");
	UserAccountDTO userDto6 = new UserAccountDTO(6, "harry", "harry123456789", "[email protected]", "35", "12390973837");
		
	/* Add row object into list. */
	List<UserAccountDTO> userAccountList = new ArrayList<UserAccountDTO>();
	userAccountList.add(userDto1);
	userAccountList.add(userDto2);
	userAccountList.add(userDto3);
	userAccountList.add(userDto4);
	userAccountList.add(userDto5);
	userAccountList.add(userDto6);
		
	/* Use "\n" as file row delimiter. */
	CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");
		
	FileWriter fWriter = null;
	
	CSVPrinter csvPrinter = null;
		
	try
	{
		System.out.println("Prepare CSVPrinter object. ");
		/* Create file writer. */
		fWriter = new FileWriter(csvFilePath);

		/* Create CSVPrinter*/
		csvPrinter = new CSVPrinter(fWriter, csvFormat);
		
		System.out.println("Print header in file. ");
		/* First create header in csv file. */
		csvPrinter.printRecord("Id", "UserName", "Password", "Email", "Age", "Mobile");

		
		System.out.println("Loop in the row list and print each row to csv file " + csvFilePath);
		/* Loop the user account list and print to csv file.*/
		for(int i=0; i<userAccountList.size(); i++)
		{
			UserAccountDTO userDto = userAccountList.get(i);
			
			List<String> rowDataList = new ArrayList<String>();
			rowDataList.add(String.valueOf(userDto.getId()));
			rowDataList.add(userDto.getUserName());
			rowDataList.add(userDto.getPassword());
			rowDataList.add(userDto.getEmail());
			rowDataList.add(userDto.getAge());
			rowDataList.add(userDto.getMobile());
			
			csvPrinter.printRecord(rowDataList);
		}
		
		System.out.println("Create file compelete successfully. ");
		
	}catch(Exception ex)
	{
		ex.printStackTrace();
	}finally
	{
		try
		{
			if(fWriter!=null)
			{
				fWriter.flush();
				fWriter.close();
			}
			
			if(csvPrinter!=null)
			{
				csvPrinter.close();
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
}

5. Read Data From CSV File Method.

This method returns a 2D List object.

public List<List<String>> readFromCsv(String csvFilePath)
{	
	List<List<String>> retList = new ArrayList<List<String>>();
		
	FileReader fReader = null;
		
	CSVParser csvParser = null;
		
	try
	{
		System.out.println("Prepare csv parser object. ");
		/* Create file reader. */
		fReader = new FileReader(csvFilePath);

		CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("Id", "UserName", "Password", "Email", "Age", "Mobile");
		/* Create csv printer*/
		csvParser = new CSVParser(fReader, csvFormat);
			
		List<CSVRecord> rowList = csvParser.getRecords();
			
		System.out.println("Loop in the csvrecords list from the second line data, and read each line from csv file " + csvFilePath);
		/* Loop the user account list and print to csv file.
		 * Because the first line in csv file is header, so start from the second row.
		 * */
		for(int i=1; i<rowList.size(); i++)
		{
			CSVRecord row = rowList.get(i);
			int id = Integer.parseInt(row.get("Id"));
			String userName = row.get("UserName");
			String password = row.get("Password");
			String email = row.get("Email");
			String age = row.get("Age");
			String mobile = row.get("Mobile");
				
			UserAccountDTO userDto = new UserAccountDTO(id, userName, password, email, age, mobile);
			System.out.println(userDto.toString());
			
			List<String> lineList = new ArrayList<String>();
			lineList.add(String.valueOf(id));
			lineList.add(userName);
			lineList.add(password);
			lineList.add(email);
			lineList.add(age);
			lineList.add(mobile);
				
			retList.add(lineList);
		}
	}catch(Exception ex)
	{
		ex.printStackTrace();
	}finally
	{
		try
		{
			if(fReader!=null)
			{
				fReader.close();
			}
			
			if(csvParser!=null)
			{
				csvParser.close();
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}
			
		return retList;
	}
}

6. Translate 2D List Object To 2D String Array.

public String[][] translateListToArray(List<List<String>> dataList)
{
	String ret[][] = null;
	if(dataList!=null)
	{
		/* Get row count. */
		int rowSize = dataList.size();
		if(rowSize>0)
		{
			List<String> rowList = dataList.get(0);
			
			/* Get column count. */
			int colSize = rowList.size();
				
			if(colSize>0)
			{
				/* Init the 2D array with the row and column count.*/
				ret = new String[rowSize][colSize];
					
				/* Loop for rows. */
				for(int i=0;i<rowSize;i++)
				{
					/* Loop the columns for each row. */
					rowList = dataList.get(i);
					for(int j=0;j<colSize;j++)
					{
						/* Assign column data in one row.*/
						ret[i][j] = rowList.get(j);
					}
				}
			}
		}
	}
	return ret;
}

7. Main Method.

ApacheCommonCsv apacheCommonCsv = new ApacheCommonCsv();
		
apacheCommonCsv.writeToCsv("C:/WorkSpace/test.csv");
		
List<List<String>> dataList = apacheCommonCsv.readFromCsv("C:/WorkSpace/test.csv");
		
String data[][] = apacheCommonCsv.translateListToArray(dataList);
		
int length = data.length;
		
System.out.println("Below is the data in the 2D array. ");
for(int i=0;i<length;i++)
{
	String row[] = data[i];
	
	StringBuffer rowBuf = new StringBuffer();
	int rowLen = row.length;
	for(int j=0;j<rowLen;j++)
	{
		rowBuf.append(row[j]);
		rowBuf.append(" , ");
	}
	
	System.out.println(rowBuf.toString());
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x