How To Read CSV File Using Java

Introduction

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

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

I am 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 you will see later in the example.

I 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.

Prerequisites

Java 1.8+

Read CSV FIle

The following code snippet read CSV file. Here I have used Java’s new feature Path and Files API.

public static void readCsv(final String fileName) throws IOException {
	Path path = Paths.get(fileName);
	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);
	}
}

Or even you can use Java’s Stream API to skip the header line and read the file more easily:

public static void readCsv2(final String fileName) throws IOException {
	Path path = Paths.get(fileName);
	Stream<String> lines = Files.lines(path).skip(1); // skipping the header

	lines.forEach(line -> {
		String[] info = line.split(",");

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

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

	lines.close();
}

Testing CSV File Reading

Executing the above code (both code snippets) 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

Source Code

Download

Leave a Reply

Your email address will not be published.