Read CSV File in Java using Scanner

Filed Under: Java

We can use Java Scanner Class to read CSV File in java.

Read CSV File in Java

Read CSV File in Java, Java Read CSV File

We can use Java Scanner class to read CSV file and convert to collection of java bean. For example, we might have a CSV file like below.

employees.csv


1,Pankaj Kumar,Developer,5000 USD
2,Mani,Programmer,4000 USD
3,Avinash,Developer,5000 USD
4,David,QA Lead,4000 USD

And we have a java bean that maps to different columns in the CSV file.

Employee.java


package com.journaldev.csv;

public class Employee {

	private int id;
	private String name;
	private String role;
	private String salary;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	public String getSalary() {
		return salary;
	}
	public void setSalary(String salary) {
		this.salary = salary;
	}
	
	@Override
	public String toString(){
		return "\nID="+getId()+"::Name"+getName()+"::Role="+getRole()+"::Salary="+getSalary();
	}
}

Let’s say that employee bean variables maps to following columns in CSV file.

1st Column – Employee ID
2nd Column – Employee Name
3rd Column – Employee Role
4th Column – Employee Salary

Now we can use Scanner class to parse CSV file and create collection of Employees.

ReadCSVWithScanner.java


package com.journaldev.csv;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ReadCSVWithScanner {

	public static void main(String[] args) throws IOException {
		// open file input stream
		BufferedReader reader = new BufferedReader(new FileReader(
				"employees.csv"));

		// read file line by line
		String line = null;
		Scanner scanner = null;
		int index = 0;
		List<Employee> empList = new ArrayList<>();

		while ((line = reader.readLine()) != null) {
			Employee emp = new Employee();
			scanner = new Scanner(line);
			scanner.useDelimiter(",");
			while (scanner.hasNext()) {
				String data = scanner.next();
				if (index == 0)
					emp.setId(Integer.parseInt(data));
				else if (index == 1)
					emp.setName(data);
				else if (index == 2)
					emp.setRole(data);
				else if (index == 3)
					emp.setSalary(data);
				else
					System.out.println("invalid data::" + data);
				index++;
			}
			index = 0;
			empList.add(emp);
		}
		
		//close reader
		reader.close();
		
		System.out.println(empList);
		
	}

}

Notice that we are setting scanner delimiter as comma (,). If input file uses some other delimiter such as pipe (|) or hash (#), then all we need to do is change the delimiter pattern in above program.

Once we run above program, it prints following output.


[
ID=1::NamePankaj Kumar::Role=Developer::Salary=5000 USD, 
ID=2::NameMani::Role=Programmer::Salary=4000 USD, 
ID=3::NameAvinash::Role=Developer::Salary=5000 USD, 
ID=4::NameDavid::Role=QA Lead::Salary=4000 USD]

If you look into Scanner class constructor, you will notice that it accepts File or InputStream as input. Also it contains utility method hasNextLine() and nextLine() that we can use to parse CSV file using Scanner only.

CSVScannerExample.java


package com.journaldev.csv;

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

public class CSVScannerExample {

	public static void main(String[] args) throws IOException {
		Scanner scanner = new Scanner(new File("employees.csv"));
		Scanner dataScanner = null;
		int index = 0;
		List<Employee> empList = new ArrayList<>();
		
		while (scanner.hasNextLine()) {
			dataScanner = new Scanner(scanner.nextLine());
			dataScanner.useDelimiter(",");
			Employee emp = new Employee();

			while (dataScanner.hasNext()) {
				String data = dataScanner.next();
				if (index == 0)
					emp.setId(Integer.parseInt(data));
				else if (index == 1)
					emp.setName(data);
				else if (index == 2)
					emp.setRole(data);
				else if (index == 3)
					emp.setSalary(data);
				else
					System.out.println("invalid data::" + data);
				index++;
			}
			index = 0;
			empList.add(emp);
		}

		scanner.close();

		System.out.println(empList);

	}

}

If you run above program, the output produced will be same as above program. Scanner class is a good choice if all you need is to parse a simple CSV file.

Comments

  1. Habib Yeshab says:

    Very good explanation. But how to do with two tables csv with different column number?

  2. Paulous Kunda says:

    Do you have any example on how to read excel files?

    1. Pankaj says:

      Apache POI is an excellent library to work with excel files.

  3. krihskapayr says:

    Nice explanation

  4. Harish says:

    How to handle if the data value contains comma?

  5. kiran says:

    How to parse a java file

    1. Pankaj says:

      Why do u want to parse a java file?

  6. Joe says:

    This was an excellent example. It gave me everything I needed, including the exact Java libraries needed. I implemented it exactly the way you did it and it worked beautifully. Thanks for doing this.

    Now I need to learn how to access the objects that you stored in the ArrayList. I’m not sure how to do that. I hope you have another example showing us how to use this. 🙂

  7. Suresh says:

    How to find out the Csv file has how many columns ? Please tell me I am totally new to (java) and this Kind of tasks? Please help me .

  8. Manish says:

    Good one.. nice article…

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages