split a csv file in java

split a csv file in java

csv file

‮:ot refer‬lautturi.com
First Name,Last Name,Display Name,Office Number
Chris,Green,Chris Green,123451
Ben,Andrews,Ben Andrews,123452
Tomm,Longmuir,Tomm Longmuir,123453
Cynthia,Carey,Cynthia Carey,123454
Melissa,MacBeth,Melissa MacBeth,123455

read csv file in java

/**
 * @author lautturi.com
 * Java example: split a csv file to fields in java
 */

import java.util.*;
import java.awt.Color;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Lautturi {

	public static void main(String[] args) {

		Path  filePath = Paths.get("F:\\test\\", "hello", "test.csv");

		try {
			List<String> lines = Files.readAllLines(filePath);
			for (int i = 0; i < lines.size(); i++) {
				String line = lines.get(i);
				System.out.println(line);
				String[] splitted = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)", -1);
				System.out.println(Arrays.toString(splitted));
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

output:

First Name,Last Name,Display Name,Office Number
[First Name, Last Name, Display Name, Office Number]
Chris,Green,Chris Green,123451
[Chris, Green, Chris Green, 123451]
Ben,Andrews,Ben Andrews,123452
[Ben, Andrews, Ben Andrews, 123452]
Tomm,Longmuir,Tomm Longmuir,123453
[Tomm, Longmuir, Tomm Longmuir, 123453]
Cynthia,Carey,Cynthia Carey,123454
[Cynthia, Carey, Cynthia Carey, 123454]
Melissa,MacBeth,Melissa MacBeth,123455
[Melissa, MacBeth, Melissa MacBeth, 123455]
Created Time:2017-09-22 18:01:13  Author:lautturi