Gradle library:
compile "org.apache.commons:commons-csv:1.5"
Sample CSV File:
Name,Email,Phone,Country
Long Do Thanh,thelongdt@gmail.com,+8499999999,Vietnam
Shane Long,Shane.Long@example.com,+1-1111111111,United States
Michael Sharry,Michael.Sharry@example.com,+1-2222222222,United States
Read CSV by column:
String path = "./sample2.csv";
Reader reader = Files.newBufferedReader(Paths.get(path));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
for (CSVRecord csvRecord : csvParser) {
// Accessing Values by Column Index
String name = csvRecord.get(0);
String email = csvRecord.get(1);
String phone = csvRecord.get(2);
String country = csvRecord.get(3);
System.out.println("Record No - " + csvRecord.getRecordNumber());
System.out.println("---------------");
System.out.println("Name : " + name);
System.out.println("Email : " + email);
System.out.println("Phone : " + phone);
System.out.println("Country : " + country);
System.out.println("---------------\n\n");
}
Write CSV
String SAMPLE_CSV_FILE = "./sample.csv";
BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE));
CSVFormat csvFormat = CSVFormat.DEFAULT.withEscape('\\');
CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat
.withHeader("RestaurantName", "URL", "Rewards", "Rewards Signup", "Gift Cards", "Find Card",
"Online Order"));
csvPrinter.flush();
csvPrinter.printRecord("Anchor Stone Deck Pizza", "http://www.anchorpizzeria.com/", "1", "2", "3", "4");
csvPrinter.flush();