Java CSV from toCSVLine(String[] strArray)

Here you can find the source of toCSVLine(String[] strArray)

Description

to CSV Line

License

Apache License

Declaration

public static String toCSVLine(String[] strArray) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.ArrayList;

public class Main {

    public static String toCSVLine(String[] strArray) {
        if (strArray == null) {
            return "";
        }// w  w  w . java 2  s. c  om
        StringBuffer cvsLine = new StringBuffer();
        for (int idx = 0; idx < strArray.length; idx++) {
            String item = addQuote(strArray[idx]);
            cvsLine.append(item);
            if (strArray.length - 1 != idx) {
                cvsLine.append(',');
            }
        }
        return cvsLine.toString();
    }

    public String toCSVLine(ArrayList<String> strArrList) {
        if (strArrList == null) {
            return "";
        }
        String[] strArray = new String[strArrList.size()];
        for (int idx = 0; idx < strArrList.size(); idx++) {
            strArray[idx] = (String) strArrList.get(idx);
        }
        return toCSVLine(strArray);
    }

    private static String addQuote(String item) {
        if (item == null || item.length() == 0) {
            return "\"\"";
        }
        StringBuffer sb = new StringBuffer();
        sb.append('"');
        for (int idx = 0; idx < item.length(); idx++) {
            char ch = item.charAt(idx);
            if ('"' == ch) {
                sb.append("\"\"");
            } else {
                sb.append(ch);
            }
        }
        sb.append('"');
        return sb.toString();
    }
}

Related

  1. toCsv(List list)
  2. toCsv(List list)
  3. toCsv(List strs)
  4. toCSV(List list)
  5. toCSV(Set list)
  6. toCSVString(List list, boolean quote)
  7. toCsvString(List values)
  8. toCsvString(List values)
  9. toCSVString(List values, boolean[] quoteColumn, String fieldSeparator, String quotationChar)