1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sourceforge.addam.impexp.csv;
20
21 import java.io.IOException;
22 import java.io.Reader;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26
27 /**
28 * Parses a CSV file, reading the first line as a header line containing keys;
29 * each record is returned as a map from the header line key to the column value.
30 * If any row has a different number of columns as the header row, an
31 * IndexOutOfBoundsException is thrown.
32 *
33 * @author Tim Dawson
34 * @since Sep 21, 2004
35 */
36 public class MapCSVParser extends CSVParser {
37
38 private List keys;
39
40 public MapCSVParser(Reader in) {
41 super(in);
42 }
43
44 private List getKeys() throws IOException, CSVFormatException {
45 if (keys == null) {
46 keys = readLine();
47 }
48 return keys;
49 }
50
51 public Map readMap() throws IOException, CSVFormatException {
52 List keys = getKeys();
53 List values = readLine();
54 Map returnValue = new HashMap();
55 if (values != null && values.size() > 0) {
56 if (keys.size() != values.size()) {
57 throw new IndexOutOfBoundsException("row " + this.getLineNumber() +
58 " has " + values.size() + " instead of " + keys.size());
59 }
60
61 for (int i = 0; i < keys.size(); i++) {
62 returnValue.put(keys.get(i), values.get(i));
63 }
64 }
65
66 return returnValue;
67 }
68 }