Difference between revisions of "Load comma seperated values (CSV) from a file into memory"

From CodeCodex

 
m
Line 36: Line 36:
 
[[Category:Java]]
 
[[Category:Java]]
 
[[Category:CSV]]
 
[[Category:CSV]]
[[Category:IO]]
+
[[Category:I/O]]

Revision as of 21:53, 1 January 2007

Implementations

Java

The following code uses the free library CSVReader. You must download this library to use the code below.

Sample Code

	CsvReader reader = new CsvReader("products.csv");

	reader.readHeaders();

	while (reader.readRecord())
	{
		String productID = reader.get("ProductID");
		String productName = reader.get("ProductName");
		String supplierID = reader.get("SupplierID");
		String categoryID = reader.get("CategoryID");
		String quantityPerUnit = reader.get("QuantityPerUnit");
		String unitPrice = reader.get("UnitPrice");
		String unitsInStock = reader.get("UnitsInStock");
		String unitsOnOrder = reader.get("UnitsOnOrder");
		String reorderLevel = reader.get("ReorderLevel");
		String discontinued = reader.get("Discontinued");
		
		// perform program logic here

	}

	reader.close();

Source File Format

	ProductID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued
	1,Chai,1,1,10 boxes x 20 bags,18,39,0,10,FALSE
	2,Chang,1,1,24 - 12 oz bottles,19,17,40,25,FALSE
	...