View Javadoc

1   /*
2    * Copyright (c) 2004 International Decision Systems, Inc.  All Rights Reserved.
3    *
4    * By using this Software, You acknowledge that the Software is a valuable asset
5    * and trade secret of either International Decision Systems, Inc. ("IDSI") or a
6    * third party supplier of IDSI and constitutes confidential and proprietary
7    * information.
8    *
9    * NEITHER IDSI NOR ANY AGENT OR PERSON ACTING FOR OR WITH IDSI HAS MADE OR DOES
10   * MAKE ANY STATEMENTS, AFFIRMATIONS, REPRESENTATIONS OR WARRANTIES WHATSOEVER
11   * TO YOU, WHETHER EXPRESS OR IMPLIED, AS TO THE SOFTWARE, THE QUALITY OR
12   * CONDITION OF THE SOFTWARE, OR THE OPERATING CHARACTERISTICS OR RELIABILITY OF
13   * THE SOFTWARE, OR ITS SUITABILITY FOR ANY GENERAL OR PARTICULAR PURPOSE, OR AS
14   * TO ANY OTHER MATTER WHATSOEVER; ANY AND ALL OTHER WARRANTIES INCLUDING
15   * WITHOUT LIMITATION ANY WARRANTIES IMPLIED BY LAW, SUCH AS THE IMPLIED
16   * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND TITLE,
17   * USE AND NON-INFRINGEMENT; ARE HEREBY EXPRESSLY DISCLAIMED AND EXCLUDED.
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  }