November 02, 2009

CSV File Handling in Java

« JAX WS Example | Main | Java CLI »
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:
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

Technorati Tags:

Posted by rafael.sobek at 12:11 AM in Java

 

[Trackback URL for this entry]

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« November »
SunMonTueWedThuFriSat
1234567
891011121314
15161718192021
22232425262728
2930