package org.xmlsh.commands.util; import java.util.ArrayList; /** * * * @author David A. Lee * @version $Revision$ */ public class CSVParser { private char mDelim = ','; // csv private char mQuote = '"'; private int mMax ; public CSVParser() { } public CSVParser( char delim , char quote ) { mDelim = delim ; mQuote = quote ; mMax = 0; } public CSVParser( char delim , char quote , int max ) { mDelim = delim ; mQuote = quote ; mMax = max ; } /** * Parse a single line into String[] each string is 1 csv field * If combine */ public CSVRecord parseLine( String line ){ if( line == null ) return null; ArrayList<String>v = new ArrayList<String>(); int len = line.length(); char c; int i; boolean sof = true ; // start of field StringBuffer buf = new StringBuffer(); for( i = 0 ; i < len ; ) { c = line.charAt(i++); if( c == mDelim && (mMax <= 0 || mMax > v.size() )){ v.add( buf.toString()); buf = new StringBuffer(); sof = true ; continue; } // Start quotes only recognized at sof if( sof && c == mQuote ){ while ( i < len ){ c = line.charAt(i++); if( c == mQuote ){ if( i == len || (i < len && line.charAt(i) != mQuote ) ) break; c = line.charAt(i++); } buf.append(c); } } else buf.append(c); sof=false ; } // Left over data - add a new field or combine with the last one if( i>0 ){ if( mMax <= 0 || mMax > v.size() ) v.add( buf.toString()); else { int last = v.size() - 1; v.set( last , v.get(last) + buf.toString() ); } } return new CSVRecord( (String[]) v.toArray( new String[ v.size() ] ) ); } } // // //Copyright (C) 2008-2014 David A. Lee. // //The contents of this file are subject to the "Simplified BSD License" (the "License"); //you may not use this file except in compliance with the License. You may obtain a copy of the //License at http://www.opensource.org/licenses/bsd-license.php // //Software distributed under the License is distributed on an "AS IS" basis, //WITHOUT WARRANTY OF ANY KIND, either express or implied. //See the License for the specific language governing rights and limitations under the License. // //The Original Code is: all this file. // //The Initial Developer of the Original Code is David A. Lee // //Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved. // //Contributor(s): none. //