from CSV Lineto Array - Java File Path IO

Java examples for File Path IO:CSV File

Description

from CSV Lineto Array

Demo Code


//package com.java2s;

import java.util.ArrayList;

public class Main {

    public static ArrayList<String> fromCSVLinetoArray(String source) {
        if (source == null || source.length() == 0) {
            return new ArrayList<String>();
        }/*  w w w  .  j a  v  a  2 s .c  om*/
        int currentPosition = 0;
        int maxPosition = source.length();
        int nextComma = 0;
        ArrayList<String> rtnArray = new ArrayList<String>();
        while (currentPosition < maxPosition) {
            nextComma = nextComma(source, currentPosition);
            rtnArray.add(nextToken(source, currentPosition, nextComma));
            currentPosition = nextComma + 1;
            if (currentPosition == maxPosition) {
                rtnArray.add("");
            }
        }
        return rtnArray;
    }

    private static int nextComma(String source, int st) {
        int maxPosition = source.length();
        boolean inquote = false;
        while (st < maxPosition) {
            char ch = source.charAt(st);
            if (!inquote && ch == ',') {
                break;
            } else if ('"' == ch) {
                inquote = !inquote;
            }
            st++;
        }
        return st;
    }

    private static String nextToken(String source, int st, int nextComma) {
        StringBuffer strb = new StringBuffer();
        int next = st;
        while (next < nextComma) {
            char ch = source.charAt(next++);
            if (ch == '"') {
                if ((st + 1 < next && next < nextComma)
                        && (source.charAt(next) == '"')) {
                    strb.append(ch);
                    next++;
                }
            } else {
                strb.append(ch);
            }
        }
        return strb.toString();
    }
}

Related Tutorials