Posted In: Java Core

How to read and parse CSV file using Scanner

Consider this code only as a example and do not use to read CSV files in a application. Use Open CSV or Apache Commons CSV to do it correctly.

Apache Commons CSV
Open CSV

Example will not work with elements with comma inside quotes


package com.example.csv;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import org.junit.Test;

public class CvsScanner {

	@Test
	public void parser1() throws Exception {
		System.out.println("\nparser1 started");
		String filepath= "E:/files/cm24AUG2017bhav.csv";
		Scanner scanner = null;

		try {
			File file = new File(filepath);
			scanner = new Scanner(file);
			scanner.useDelimiter(",");
			while (scanner.hasNext()) {
				String data = scanner.next();
				System.out.println("Element =" + data);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			scanner.close();
		}
	}
}

Tags:

by , on August 31st, 2017

  • Categories