Java CSV File Parse csvSplitLine(String line, char fieldSeparator)

Here you can find the source of csvSplitLine(String line, char fieldSeparator)

Description

Basic CSV line splitting that takes quotes into account.

License

Open Source License

Declaration

public static String[] csvSplitLine(String line, char fieldSeparator) 

Method Source Code

//package com.java2s;

import java.util.*;

public class Main {
    /**/*from w  w  w  .  j  a va  2 s.c  om*/
     * Basic CSV line splitting that takes quotes into account.
     * Doesn't do any error checking, e.g., mis-matched quotes.
     */
    public static String[] csvSplitLine(String line, char fieldSeparator) {
        LinkedList<String> fields = new LinkedList<String>();
        boolean inQuote = false; // whether inside a quotation
        String field = "";
        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) == '\"') {
                if (inQuote && i + 1 != line.length()
                        && line.charAt(i + 1) == '\"') {
                    field += '\"';
                    i++; // skip over quote escape
                } else {
                    inQuote = !inQuote;
                }
            } else if (!inQuote && line.charAt(i) == fieldSeparator) {
                fields.add(field);
                field = "";
            } else {
                field += line.charAt(i);
            }
        }
        fields.add(field); // after last ','

        return fields.toArray(new String[0]);
    }
}

Related

  1. csvLineParse(String line, char delimiter)
  2. parse(final String csvString)
  3. parseCsv(InputStream csvInput)
  4. parseCsv(InputStream fileStream)
  5. parseCSV(String csv)