1 package com.opencsv.bean.concurrent;
2
3 import com.opencsv.CSVReader;
4 import com.opencsv.bean.CsvToBean;
5 import com.opencsv.exceptions.CsvValidationException;
6 import org.apache.commons.lang3.StringUtils;
7
8 import java.io.IOException;
9
10 /**
11 * This class exists to isolate the logic for reading a single line of input
12 * that is common to {@link CsvToBean#iterator()} and {@link CompleteFileReader}.
13 * It is not meant for end user consumption.
14 * @author Andrew Rucker Jones
15 * @since 5.2
16 */
17 public class SingleLineReader {
18 protected final CSVReader csvReader;
19 protected final boolean ignoreEmptyLines;
20
21 /** Stores the result of parsing a line of input. */
22 protected String[] line;
23
24 /**
25 * The only constructor.
26 * @param csvReader The {@link CSVReader} for reading the input
27 * @param ignoreEmptyLines Whether blank lines of input should be ignored
28 */
29 public SingleLineReader(CSVReader csvReader, boolean ignoreEmptyLines) {
30 this.csvReader = csvReader;
31 this.ignoreEmptyLines = ignoreEmptyLines;
32 }
33
34 private boolean isCurrentLineEmpty() {
35 return line.length == 0 || (line.length == 1 && StringUtils.isEmpty(line[0]));
36 }
37
38 /**
39 * Reads from the {@link CSVReader} provided on instantiation until a
40 * usable line of input is found.
41 *
42 * @return The next line of significant input, or {@code null} if none
43 * remain
44 * @throws IOException If bad things happen during the read
45 * @throws CsvValidationException If a user-defined validator fails
46 */
47 public String[] readNextLine() throws IOException, CsvValidationException {
48 do {
49 line = csvReader.readNext();
50 } while (line != null && isCurrentLineEmpty() && ignoreEmptyLines);
51 return getLine();
52 }
53
54 /**
55 * @return The number of lines read from the input this far
56 */
57 public long getLinesRead() {return csvReader.getLinesRead();}
58
59 /**
60 * Returns a copy of the last line read by {@link #readNextLine()}.
61 * @return A new array with the last line read
62 */
63 public String[] getLine() {
64 String[] lineCopy = line;
65 if(line != null) {
66 lineCopy = new String[line.length];
67 System.arraycopy(line, 0, lineCopy, 0, line.length);
68 }
69 return lineCopy;
70 }
71 }