1

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

4

2 回答 2

8

您可能最好使用图书馆。CSV 解析起来非常棘手。看看 OpenCSV:

http://opencsv.sourceforge.net/

CSVParser parser = new CSVParser();
String[] fields = parser.parseLine(line);
于 2013-10-28T03:33:04.550 回答
3

StringTokenizer对于您尝试做的事情来说有点繁重(同时,如果您希望用双引号解析确切的 CSV 格式,则不够复杂)。

一种更简单的方法是使用String.split方法,如下所示:

public WarehouseItem(String warehouseItem) {
    String key, brand, model;
    int weightInKG;
    double price; 
    String[] tok = warehouseItem.split(",");
    if (tok.length != 5) {
        throw new IllegalStateException("Invalid CSV: not enough columns");
    }
    key = tok[0];
    brand = tok[1];
    model = tok[2];
    weightInKG = Integer.parseInt(tok[3]);
    price = Double.valueOf(tok[4]);
    // Do something with the values you've got
    ...
}
于 2013-10-28T03:28:25.837 回答