Posted In: Java Core, String

How to read and parse CSV file using Guava Splitter

Splitting a comma-separated string but ignoring commas in quotes

Maven guava

<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>23.0</version>
</dependency>

Guava Splitter

import com.google.common.base.Splitter;

Works only without commas in quotes data

@Test
// Works only without commas in quotes data
public void guavasplitter1() throws Exception {
	System.out.println("\nguavasplitter1 started");
	try {
		String line = "3MINDIA,EQ,14450,14900,868,INE470,A01017";
		Splitter splitter = Splitter.on(',');
		List<String> list = splitter.splitToList(line);
		System.out.println(list);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Works with commas in quotes data

@Test
// Works only with commas in quotes data
public void guavasplitter2() throws Exception {
	System.out.println("\nguavasplitter2 started");
	try {
		String line = "\"3MIN,DIA\",EQ,14450,14900,868,\"INE470,A01017\"";
		Pattern pattern = Pattern.compile(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");			
		Splitter splitter = Splitter.on(pattern);
		List<String> list = splitter.splitToList(line);
		System.out.println(list);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Tags:

by , on August 29th, 2017

  • Categories