The JavaCSV projects helps the Java developer to read and write CSV files. It represents an API, which works similarly as the JDBC ResultSet. It offers an iterator for reading single rows and access the columns based on the column title. The following example describes how the API e.g. can be used.
Example CSV file:
Rafael Sobek
Example CSV file:
orderId;productName;productId;count; 2;Simple T-Shirt;31;2; 1;Nerd T-Shirt;12;4; ...You can write this CSV with the following Java code:
CsvWriter writer = new CsvWriter("mytest.csv");
writer.setDelimiter(';');
writer.writeRecord("orderId;productName;productId;count".split(";"));
writer.writeRecord("2;Simple T-Shirt;31;2".split(";"));
writer.writeRecord("1;Nerd T-Shirt;12;4".split(";"));
writer.close();
To read the CSV file you have to use the CSVReader:
CsvReader csvreader = new CsvReader(new InputStreamReader(new FileInputStream("mytest.csv"), "UTF-8"));
csvreader.setDelimiter(';');
csvreader.readHeaders();
while (csvreader.readRecord()) {
System.out.println("Get the product name and count: " + csvreader.get("count") + " x " csvreader.get("productName"));
}
Regards,Rafael Sobek
