Java CSV File Parse csvLineParse(String line, char delimiter)

Here you can find the source of csvLineParse(String line, char delimiter)

Description

csv Line Parse

License

EUPL

Declaration

public static List<String> csvLineParse(String line, char delimiter) 

Method Source Code

//package com.java2s;
/*//from ww  w  .j  a  v a2s  . com
 * Copyright 2011, 2012 Delving BV
 *
 *  Licensed under the EUPL, Version 1.0 or? as soon they
 *  will be approved by the European Commission - subsequent
 *  versions of the EUPL (the "Licence");
 *  you may not use this work except in compliance with the
 *  Licence.
 *  You may obtain a copy of the Licence at:
 *
 *  http://ec.europa.eu/idabc/eupl
 *
 *  Unless required by applicable law or agreed to in
 *  writing, software distributed under the Licence is
 *  distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 *  express or implied.
 *  See the Licence for the specific language governing
 *  permissions and limitations under the Licence.
 */

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static List<String> csvLineParse(String line, char delimiter) {
        List<String> strings = new ArrayList<String>();
        boolean inQuotes = false;
        StringBuilder field = new StringBuilder();
        for (int walk = 0; walk < line.length(); walk++) {
            char ch = line.charAt(walk);
            if (ch == delimiter) {
                if (inQuotes) {
                    field.append(ch);
                } else {
                    strings.add(field.toString().trim());
                    field.setLength(0);
                }
            } else
                switch (ch) {
                case '"':
                    if (inQuotes) {
                        if (walk + 1 < line.length() && line.charAt(walk + 1) == '"') { // two quotes escapes one
                            field.append('"');
                            walk++; // skip the next char, it's a quote
                        } else {
                            inQuotes = false;
                        }
                    } else {
                        inQuotes = true;
                    }
                    break;
                //                case '\t':
                //                case ' ':
                //                    if (inQuotes) field.append(ch);
                //                    break;
                default:
                    field.append(ch);
                }
        }
        strings.add(field.toString().trim());
        return strings;
    }
}

Related

  1. csvSplitLine(String line, char fieldSeparator)
  2. parse(final String csvString)
  3. parseCsv(InputStream csvInput)
  4. parseCsv(InputStream fileStream)