In this tutorial I will show you how to read CSV file using Java 7 or later versions. We will use here Java’s new feature Path API.

We will also use Java 8’s Stream API to split the comma separated line and map the record into String array.

We are going to show you how to read file content into byte array and how to convert byte array into String.

If you would like to skip headers then you can do so by using boolean flag, which we will see later in the example.

We convert the array of String into a list of String.

You can print the array of String using Arrays.toString() or iterating one by one over the array.

Example

package com.roytuts.java.read.csv.file;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class CsvReader {

	public static void main(String[] args) throws IOException {
		Path path = Paths.get("C:/jee_workspace/sample.csv");
		byte[] bytes = Files.readAllBytes(path);

		String str = new String(bytes);

		String[] splitted = Arrays.stream(str.split("\n")).map(String::trim).toArray(String[]::new);

		// System.out.println(Arrays.toString(splitted));

		List<String> list = Arrays.asList(splitted);

		//System.out.println();

		boolean skipHeader = true;

		for (String string : list) {
			String[] line = Arrays.stream(string.split(",")).map(String::trim).toArray(String[]::new);

			// System.out.println(Arrays.toString(line));

			if (skipHeader) {
				skipHeader = false;
				continue;
			}

			String sl = line[0];
			String id = line[1];
			String name = line[2];
			String manager = line[3];

			System.out.println("Sl No: " + sl + ", ID: " + id + ", Name: " + name + ", Manager: " + manager);
		}
	}

}

Executing the above code will give you the below output:

Sl No: 1, ID: 100737, Name: Achtar, Manager: Mahmoud
Sl No: 2, ID: 100979, Name: Binraj, Manager: Gireesh
Sl No: 3, ID: 900859, Name: Mohan, Manager: Amjad
Sl No: 4, ID: 100845, Name: KUSELAN, Manager: Biju

Sample CSV File

Source Code

Download

Thanks for reading.

Tags:

Leave a Reply

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