View Javadoc
1   package com.opencsv;
2   
3   import com.opencsv.exceptions.CsvValidationException;
4   import org.apache.commons.lang3.ObjectUtils;
5   
6   import java.io.IOException;
7   import java.util.Iterator;
8   import java.util.Locale;
9   import java.util.NoSuchElementException;
10  import java.util.ResourceBundle;
11  
12  /**
13   * Provides an Iterator over the data found in opencsv.
14   * <p><em>Fair warning!</em> This mechanism of getting at the data opencsv
15   * delivers has limitations when used with the opencsv annotations. Locales and
16   * custom converters are not supported. Further features may or may not work.</p>
17   */
18  public class CSVIterator implements Iterator<String[]> {
19     private final CSVReader reader;
20     private String[] nextLine;
21     
22     /** Locale for all translations. */
23     private Locale errorLocale = Locale.getDefault();
24  
25     /**
26      * @param reader Reader for the CSV data.
27      * @throws IOException If unable to read data from the reader.
28      * @throws CsvValidationException if custom defined validator fails.
29      */
30     public CSVIterator(CSVReader reader) throws IOException, CsvValidationException {
31        this.reader = reader;
32        nextLine = reader.readNext();
33     }
34     
35      /**
36       * Sets the locale for error messages.
37       * @param errorLocale Locale for error messages. If null, the default locale
38       *   is used.
39       * @since 4.0
40       */
41      public void setErrorLocale(Locale errorLocale) {
42          this.errorLocale = ObjectUtils.defaultIfNull(errorLocale, Locale.getDefault());
43      }
44      
45     /**
46      * Returns true if the iteration has more elements.
47      * In other words, returns true if {@link #next()} would return an element
48      * rather than throwing an exception.
49      *
50      * @return True if the CSVIterator has more elements.
51      */
52     @Override
53     public boolean hasNext() {
54        return nextLine != null;
55     }
56  
57     /**
58      *
59      * Returns the next element in the iterator.
60      *
61      * @return The next element of the iterator.
62      */
63     @Override
64     public String[] next() {
65        String[] temp = nextLine;
66        try {
67           nextLine = reader.readNext();
68        } catch (IOException | CsvValidationException e) {
69           NoSuchElementException nse = new NoSuchElementException(e.getLocalizedMessage());
70           nse.initCause(e);
71           throw nse;
72        }
73        return temp;
74     }
75  
76     /**
77      * This method is not supported by opencsv and will throw an
78      * {@link java.lang.UnsupportedOperationException} if called.
79      */
80     @Override
81     public void remove() {
82        throw new UnsupportedOperationException(ResourceBundle.getBundle(ICSVParser.DEFAULT_BUNDLE_NAME, errorLocale).getString("read.only.iterator"));
83     }
84  }