Class CSVParser

java.lang.Object
com.codename1.io.CSVParser

public class CSVParser extends Object

The CSVParser allows importing data into applications quickly from a CSV source. CSV is a file format that is supported by all spreadsheets and most databases for data exchange.

The sample below lists a simple hardcoded CSV within the table:

Form hi = new Form("CSV Parsing", new BorderLayout());
CSVParser parser = new CSVParser();
try(Reader r = new com.codename1.io.CharArrayReader("1997,Ford,E350,\"Super, \"\"luxurious\"\" truck\"".toCharArray())) {
    String[][] data = parser.parse(r);
    String[] columnNames = new String[data[0].length];
    for(int iter=  0 ; iter < columnNames.length ; iter++) {
        columnNames[iter] = "Col " + (iter + 1);
    }
    TableModel tm = new DefaultTableModel(columnNames, data);
    hi.add(BorderLayout.CENTER, new com.codename1.ui.table.Table(tm));
} catch(IOException err) {
    Log.e(err);
}
hi.show();

A large file does not have to be held in memory as a whole: parse(Reader, RowHandler) hands over one row at a time. That method is also the stricter of the two. It keeps empty lines as empty rows and keeps a trailing empty value, where the array returning methods skip both, as they always have.

Files that spreadsheets save differ in ways a file name does not tell: the separator follows the locale of the machine (a semicolon where the comma is the decimal mark) and "Unicode text" is tab separated UTF-16. setDetectSeparator(boolean) picks the separator from the content, and the InputStream methods read a UTF-16 byte order mark. A UTF-8 byte order mark is dropped by every method.

  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static interface 
    Receives the rows of parse(Reader, RowHandler) as they are read.
  • Constructor Summary

    Constructors
    Constructor
    Description
    Initializes a parser with the default comma (',') separator char
    CSVParser(char separatorChar)
    Allows creating a parser with a custom separator char
  • Method Summary

    Modifier and Type
    Method
    Description
    static char
    detectSeparator(String sample, char fallback)
    Picks the separator of a piece of separated text: the comma, the semicolon, the tab or the vertical bar, whichever splits its lines most consistently.
    char
    The character that encloses a value containing a separator or a line break, a double quote unless changed.
    char
    The separator in use.
    boolean
    Whether the separator is picked from the content of each file.
    String[][]
    Parses input from the given stream and returns the tokens broken into rows and columns.
    void
    Parses input from the given stream one row at a time, see parse(Reader, RowHandler).
    String[][]
    parse(InputStream r, String encoding)
    Parses input from the given stream and returns the tokens broken into rows and columns.
    String[][]
    Parses input from the given reader and returns the tokens broken into rows and columns
    void
    Parses input from the given reader one row at a time, without holding the file in memory.
    void
    setDetectSeparator(boolean detectSeparator)
    Picks the separator from the content of each file instead of using the one this parser was created with.
    void
    setQuoteChar(char quoteChar)
    Changes the character that encloses a value containing a separator or a line break.

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • CSVParser

      public CSVParser()
      Initializes a parser with the default comma (',') separator char
    • CSVParser

      public CSVParser(char separatorChar)

      Allows creating a parser with a custom separator char

      Parameters
      • separatorChar: custom separator character such as semi-colon (';') etc.
  • Method Details

    • getSeparatorChar

      public char getSeparatorChar()

      The separator in use. After a parse with setDetectSeparator(boolean) on, this is the separator that was detected.

      Returns

      the separator character

    • getQuoteChar

      public char getQuoteChar()

      The character that encloses a value containing a separator or a line break, a double quote unless changed.

      Returns

      the quote character

    • setQuoteChar

      public void setQuoteChar(char quoteChar)

      Changes the character that encloses a value containing a separator or a line break. Within such a value the character is written twice to stand for itself.

      Parameters
      • quoteChar: the quote character, a double quote by default
    • isDetectSeparator

      public boolean isDetectSeparator()

      Whether the separator is picked from the content of each file.

      Returns

      true if the separator is detected

    • setDetectSeparator

      public void setDetectSeparator(boolean detectSeparator)

      Picks the separator from the content of each file instead of using the one this parser was created with. A first line of the form sep=;, which spreadsheets write and read, names the separator outright and is not returned as a row. Otherwise the comma, the semicolon, the tab and the vertical bar are counted outside quoted values in the first lines, and the one that splits every line into the same number of values wins. A file where none of them appears keeps the separator this parser was created with.

      Parameters
      • detectSeparator: true to detect the separator
    • detectSeparator

      public static char detectSeparator(String sample, char fallback)

      Picks the separator of a piece of separated text: the comma, the semicolon, the tab or the vertical bar, whichever splits its lines most consistently. Quoted values are skipped, so a comma inside a quoted address does not count.

      Parameters
      • sample: the beginning of the text, a few lines are enough

      • fallback: the answer when none of the candidates appears

      Returns

      the separator

    • parse

      public String[][] parse(InputStream r) throws IOException

      Parses input from the given stream and returns the tokens broken into rows and columns. The stream is read as UTF-8, without the byte order mark a file may start with, and as UTF-16 when it starts with that encoding's byte order mark, as Excel's "Unicode text" does. The mark is therefore never part of the first cell.

      Parameters
      • r: the input stream
      Returns

      array of rows and columns

      Throws:
      IOException
    • parse

      public void parse(InputStream r, CSVParser.RowHandler handler) throws IOException

      Parses input from the given stream one row at a time, see parse(Reader, RowHandler). The stream is read as UTF-8 unless it starts with a UTF-16 byte order mark.

      Parameters
      • r: the input stream, closed when the method returns

      • handler: receives the rows

      Throws
      • java.io.IOException: if the stream cannot be read
      Throws:
      IOException
    • parse

      public String[][] parse(InputStream r, String encoding) throws IOException

      Parses input from the given stream and returns the tokens broken into rows and columns. The stream is read as UTF-8, without the byte order mark a file may start with, and as UTF-16 when it starts with that encoding's byte order mark, as Excel's "Unicode text" does. The mark is therefore never part of the first cell.

      Parameters
      • r: the input stream

      • encoding: the encoding of the stream

      Returns

      array of rows and columns

      Throws:
      IOException
    • parse

      public String[][] parse(Reader r) throws IOException

      Parses input from the given reader and returns the tokens broken into rows and columns

      Parameters
      • r: the reader stream
      Returns

      array of rows and columns

      Throws:
      IOException
    • parse

      public void parse(Reader r, CSVParser.RowHandler handler) throws IOException

      Parses input from the given reader one row at a time, without holding the file in memory.

      This method reads the way a spreadsheet does, which differs from the array returning methods in three places: an empty line is a row with no values, where they skip it; a separator at the very end of the file is followed by an empty value, where they drop it; and a line ending in CR LF ends one row. A quoted value may contain separators and line breaks, and the quote character written twice inside it stands for itself.

      Parameters
      • r: the reader, closed when the method returns

      • handler: receives the rows

      Throws
      • java.io.IOException: if an exception is thrown by the reader
      Throws:
      IOException