Method to split the CSV record into tokens. - Java File Path IO

Java examples for File Path IO:CSV File

Description

Method to split the CSV record into tokens.

Demo Code


//package com.java2s;
import java.util.ArrayList;

public class Main {
    /**//from   w  ww  .ja  va  2  s.com
     * Method to split the CSV record into tokens.
     * @param line
     * @return
     */
    public static String[] splitCSVToTokens(String line) {
        if (!line.contains("\",") && !line.contains(",\""))
            return line.split(",");
        ArrayList<String> tokenList = new ArrayList<String>();

        String tokens[] = line.split("\",\"");
        String joinedTokens = null;

        for (int i = 0; i < tokens.length;) {
            /*
            if(i < tokens.length -1 && tokens[i].startsWith("\"") && tokens[i + 1].endsWith("\"") && !tokens[i].endsWith("\"") && !tokens[i + 1].startsWith("\""))
            {
              joinedTokens = tokens[i] + " " + tokens[i + 1];
              tokenList.add(joinedTokens.replaceFirst("^\"", "").replaceFirst("\"$", ""));
              i = i + 2;
            }
            else
             */
            {
                tokenList.add(tokens[i].replaceFirst("^\"", "")
                        .replaceFirst("\"$", ""));
                i = i + 1;
            }
        }

        String tokenArray[] = tokenList
                .toArray(new String[tokenList.size()]);
        return tokenArray;
    }
}

Related Tutorials