ive got this specification for a CSV file:
and i have got this code to tokenize each row:
public WarehouseItem(String warehouseItem) {
String key, brand, model;
int weightInKG;
double price;
StringTokenizer strTok;
strTok = new StringTokenizer(warehouseItem);
try {
key = strTok.nextToken();
brand = strTok.nextToken();
model = strTok.nextToken();
weightInKG = Integer.parseInt(strTok.nextToken());
price = Double.valueOf(strTok.nextToken());
}
catch (Exception e) {
throw new IllegalStateException("CSV row had invalid format");
}
}
when i try to run it i get the IllegalStateException for the CSV file.
Exception in thread "main" java.lang.IllegalStateException: CSV row had invalid format
at WarehouseItem.<init>(WarehouseItem.java:23) // throwing exception
at main.loadRecords(main.java:63) // records[numRows] = new WarehouseItem(warehouseItem); storing into array of objects
at main.main(main.java:26) // loadRecords(); calling the function which reads a line
at main.loadRecords(main.java:78) // main(null); recursing back to main
at main.main(main.java:26) // loadRecords(); calling the function which reads a line
Heres an example of a row in the CSV file:
Couch:6,Fremarc,Deluxe,101,1871.7
im thinking maybe its because key has ID as a sequence number?? or does that not matter at all?? im confused and any help would be appreciated
You're probably best off with a library. CSV can be surprisingly tricky to parse. Have a look at OpenCSV:
http://opencsv.sourceforge.net/
CSVParser parser = new CSVParser();
String[] fields = parser.parseLine(line);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With