从CSV行

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

509
从CSV行


//package com.nowjava;

/** from 
NowJava.com**/

import java.util.ArrayList;


public class Main {


    public static String[] fromCSVLine(String source, int size) {

        ArrayList<String> tmpArray = fromCSVLinetoArray(source);

        if (size < tmpArray.size()) {

            size = tmpArray.size();

        }

        String[] rtnArray = new String[size];

        tmpArray.toArray(rtnArray);
        /**
         * NowJava.com - 时  代  Java 提 供 
        **/

        return rtnArray;

    }


    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) {

            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) {

            
展开阅读全文