集册 Java实例教程 CSV记录分析器。

CSV记录分析器。

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

457
CSV记录解析器。
/*from 时 代 J a v a 公 众 号 - N o w J a v  a . c o m*/


//package com.nowjava;


import java.util.ArrayList;


import java.util.List;


public class Main {

    /**

     * CSV record parser. Convert a CSV record to a List of Strings representing the fields of the

     * CSV record. The CSV record is expected to be separated by the specified CSV field separator.

     *

     * @param record       The CSV record.

     * @param csvSeparator The CSV field separator to be used.

     * @return A List of Strings representing the fields of each CSV record.

     */

    private static List<String> parseCsvRecord(String record,

            char csvSeparator) {


        // Prepare.

        boolean quoted = false;

        StringBuilder fieldBuilder = new StringBuilder();

        List<String> fields = new ArrayList<String>();


        // Process fields./*from 时代Java*/

        for (int i = 0; i < record.length(); i++) {

            char c = record.charAt(i);

            fieldBuilder.append(c);


            if (c == '"') {

                quoted = !quoted; // Detect nested quotes.

            }


            if ((!quoted && c == csvSeparator) // The separator ..

                    || i + 1 == record.length()) // .. or, the end of record.

            {

                String field = fieldBuilder.toString() // Obtain the field, ..

                        .replaceAll(csvSeparator + "$", "") // .. trim ending separator, ..

                        .replaceAll("^\"|\"$", "") // .. trim surrounding quotes, ..

                 
展开阅读全文