try (Reader reader = Files.newBufferedReader(Paths.get("data.csv"));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT)) {
for (CSVRecord csvRecord : csvParser) {
String firstName = csvRecord.get(0);
String lastName = csvRecord.get(1);
String email = csvRecord.get(2);
// ...
}
}
try (Writer writer = Files.newBufferedWriter(Paths.get("data.csv"));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT)) {
csvPrinter.printRecord("First Name", "Last Name", "Email");
csvPrinter.printRecord("John", "Doe", "john.doe@example.com");
csvPrinter.printRecord("Jane", "Smith", "jane.smith@example.com");
// ...
}
CSVFormat csvFormat = CSVFormat.newFormat(',')
.withHeader("First Name", "Last Name", "Email")
.withSkipHeaderRecord();
try (Writer writer = Files.newBufferedWriter(Paths.get("data.csv"));
CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) {
csvPrinter.printRecord("John", "Doe", "john.doe@example.com");
csvPrinter.printRecord("Jane", "Smith", "jane.smith@example.com");
// ...
}