Read CSV File Using Java Scanner Class

Here I am demonstrating how to read / parse CSV file using java scanner class.

For example my csv file (user.csv) looks like below.

Rockey,22,India
Bill,23,US
Sonia,23,Germany


Now I am creating java class for mapping the above fields in csv file.


User.java

public class User {

    private String name;
    private int age;
    private String address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
	return "User [name=" + name + ", age=" + age + ", address=" + address + "]";
    }
    
    
}



If you check the scanner class api, you can see it supports File or InputStream as input. In below code I am using File as input.


CSVParsingExample.java

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

public class CSVParsingExample {

    public static void main(String[] args) throws IOException {
	Scanner scanner = new Scanner(new File("user.csv"));
	Scanner valueScanner = null;
	int index = 0;
	List<User> userList = new ArrayList<>();

	while (scanner.hasNextLine()) {
	    valueScanner = new Scanner(scanner.nextLine());
	    valueScanner.useDelimiter(",");
	    User user = new User();

	    while (valueScanner.hasNext()) {
		String data = valueScanner.next();
		if (index == 0){
		    user.setName(data);
		}
		else if (index == 1){
		    user.setAge(Integer.parseInt(data));
		}
		else if (index == 2){
		    user.setAddress(data);
		}
		index++;
	    }
	    index = 0;
	    userList.add(user);
	}

	scanner.close();

	System.out.println(userList);

    }

}


In the above code you can see, scanner class contains nextLine(), hasNext() methods which helps to iterate the data as per our required format.


output


[User [name=Rockey, age=22, address=India], User [name=Bill, age=23, address=US], User [name=Sonia, age=23, address=Germany]]








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