Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a single CSV line

Tags:

java

csv

ive got this specification for a CSV file:

  • Key – Structured as Category:ID, where ID is a sequence number. There is no need (or use) to split this into its two pieces, just treat the key as a single unique value
  • Brand – Manufacturer of the product
  • Model – Model name of the product
  • WeightInKg – Weight of the product,rounded to the nearest kg
  • Price – Selling price of the product to 2 decimal places (2dp)

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

like image 539
Jad Sapida Avatar asked Mar 09 '26 20:03

Jad Sapida


1 Answers

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);
like image 141
Kong Avatar answered Mar 11 '26 09:03

Kong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!