Java String Quote quoteCSV(Object val)

Here you can find the source of quoteCSV(Object val)

Description

Double quotes input string for CSV if needed: string contains ", \n, \r, ','

License

Open Source License

Declaration

public static String quoteCSV(Object val) 

Method Source Code

//package com.java2s;
/*//from   w ww  .jav  a 2 s.c  o m
 * Copyright (c) 2008, SQL Power Group Inc.
 *
 * This file is part of Power*Architect.
 *
 * Power*Architect is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Power*Architect is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

public class Main {
    /**
      * Double quotes input string for CSV if needed:
      * string contains ", \n, \r, ','
      */
    public static String quoteCSV(Object val) {
        if (val == null) {
            return "";
        } else if (val instanceof String) {
            return quoteCSVStr((String) val);
        }
        return val.toString();
    }

    public static String quoteCSVStr(String val) {
        CharSequence doubleQuote = "\"".subSequence(0, "\"".length());
        CharSequence doubleDoubleQuote = "\"\"".subSequence(0, "\"\"".length());
        CharSequence newLine = "\n".subSequence(0, "\n".length());
        CharSequence cr = "\r".subSequence(0, "\r".length());
        CharSequence comma = ",".subSequence(0, ",".length());

        if (val.contains(doubleQuote)) {
            StringBuffer sb = new StringBuffer(doubleQuote);
            sb.append(val.replace(doubleQuote, doubleDoubleQuote));
            sb.append(doubleQuote);
            return sb.toString();
        } else if (val.contains(newLine) || val.contains(cr) || val.contains(comma)) {
            StringBuffer sb = new StringBuffer(doubleQuote);
            sb.append(val);
            sb.append(doubleQuote);
            return sb.toString();
        }
        return val;
    }
}

Related

  1. quoteCharPresent(String quote)
  2. quoteComma(String value)
  3. quoteCommandArgument(String s)
  4. quoteComments(String value)
  5. quoteContentsOfNextBracket(String piece)
  6. quoteCSVValue(String value, String sep)
  7. quoted(CharSequence s)
  8. quoted(CharSequence s)
  9. quoted(final String str)