All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.rathravane.till.data.csv.csvEncoder Maven / Gradle / Ivy

There is a newer version: 2.1.1
Show newest version
package com.rathravane.till.data.csv;

public class csvEncoder
{
	public static final char kDefaultQuoteChar = '"';
	public static final char kDefaultFieldSeparatorChar = ',';

	public static String encodeForCsv ( String val )
	{
		return encodeForCsv ( val, kDefaultQuoteChar, kDefaultFieldSeparatorChar );
	}

	public static String encodeForCsv ( String val, char quoteChar, char sepChar )
	{
		String result = ""; // which means no value at all
		if ( val != null )
		{
			if ( val.length () == 0 )
			{
				// result is "\"\"" -- not the empty string
				result = "" + quoteChar + quoteChar;
			}
			else
			{
				// if the value contains the separator char, it must be escaped and wrapped in quotes
				final boolean needWrap = ( -1 != val.indexOf ( sepChar ) );
				result = escapeString ( val, quoteChar, sepChar, needWrap );
			}
		}
		return result;
	}

	private static String escapeString ( String val, char quoteChar, char sepChar, boolean needWrap )
	{
		final StringBuffer result = new StringBuffer ();
		if (needWrap) result.append ( quoteChar );

		final int len = val.length ();
		for ( int i=0; i




© 2015 - 2025 Weber Informatics LLC | Privacy Policy