集册 Java实例教程 从CSV行到数组

从CSV行到数组

欢马劈雪     最近更新时间:2020-01-02 10:19:05

421
从CSV Lineto数组


//package com.nowjava;/*N o w J a v a . c o m - 时  代  Java*/


import java.util.ArrayList;


public class Main {


    public static ArrayList<String> fromCSVLinetoArray(String source) {

        if (source == null || source.length() == 0) {

            return new ArrayList<String>();

        }

        int currentPosition = 0;

        int maxPosition = source.length();

        int nextComma = 0;

        ArrayList<String> rtnArray = new ArrayList<String>();

        while (currentPosition < maxPosition) {
        /*
        N o w J a v a . c o m - 时  代  Java
        */

            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++);

            
展开阅读全文