Java tutorial
//package com.java2s; /* * Copyright (C) 2013 4th Line GmbH, Switzerland * * The contents of this file are subject to the terms of either the GNU * Lesser General Public License Version 2 or later ("LGPL") or the * Common Development and Distribution License Version 1 or later * ("CDDL") (collectively, the "License"). You may not use this file * except in compliance with the License. See LICENSE.txt for more * information. * * This program 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. */ public class Main { /** * Converts the given instances into comma-separated elements of a string, * escaping commas with backslashes. */ public static String toCommaSeparatedList(Object[] o) { return toCommaSeparatedList(o, true, false); } /** * Converts the given instances into comma-separated elements of a string, * optionally escapes commas and double quotes with backslahses. */ public static String toCommaSeparatedList(Object[] o, boolean escapeCommas, boolean escapeDoubleQuotes) { if (o == null) { return ""; } StringBuilder sb = new StringBuilder(); for (Object obj : o) { String objString = obj.toString(); objString = objString.replaceAll("\\\\", "\\\\\\\\"); // Replace one backslash with two (nice, eh?) if (escapeCommas) { objString = objString.replaceAll(",", "\\\\,"); } if (escapeDoubleQuotes) { objString = objString.replaceAll("\"", "\\\""); } sb.append(objString).append(","); } if (sb.length() > 1) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } }