集册 Java实例教程 CSV记录格式化程序。

CSV记录格式化程序。

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

415
CSV记录格式化程序。


//package com.nowjava;
/** 
 来自 n o w    j a v a  . c o m**/


import java.util.Iterator;

import java.util.List;


public class Main {

    /**

     * CSV record formatter. Convert a List of Objects representing the fields of a CSV record to a

     * String representing the CSV record. The value of each Object will be obtained by its

     * toString() method. The fields of the CSV record will be separated by the specified CSV field

     * separator.

     *

     * @param csvRecord    A List of Objects representing the fields of a CSV reecord.

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

     * @return A String representing a CSV record.

     */

    private static <T extends Object> String formatCsvRecord(

            List<T> csvRecord, char csvSeparator) {


        // Prepare.

        StringBuilder fields = new StringBuilder();
        /*
        来 自*
         nowjava
        */

        String separator = String.valueOf(csvSeparator);


        // Process fields.

        for (Iterator<T> iter = csvRecord.iterator(); iter.hasNext();) {

            T object = iter.next();


            if (object != null) {

                String field = object.toString().replace("\"", "\"\""); // Escape quotes.


                if (field.contains(separator) || field.contains("\"")) {

                    field = "\"" + field + "\""; 
展开阅读全文