| CsvLineParser.java |
package server.servlets;
/**
* The CsvLineParser class is a utility class which
* enables extraction of values from a comma separated value,
* or CSV, file.
*
* @author Robert Lysik
* @version 1.00
*/
public class CsvLineParser {
/**
* This is the default constructor for the CsvLineParser class.
*/
public CsvLineParser() {
return;
}
/**
* This method takes the unparsed comma separated value string
* and an array of integers representing the indices of the
* strings to extract from the CSV string as arguments. The
* return value of this function is an array of the requested
* strings.
*
*/
public String[] getValues(String s, int plays[]) {
// Set the size of our array to the number of values
// requested.
String values[] = new String[plays.length];
String tokens[] = getTokens(s);
for (int index = 0; index < plays.length; index++) {
values[index] = tokens[plays[index]];
}
return values;
}
/**
* This function takes the unparsed comma separated value string
* as an argument. Each character in the string is examined to
* determine whether or not it is a comma. If so, a substring
* is extracted from the CSV string up to the comma and the
* starting index of the string is incremented one position beyond
* the location of the comma.
*/
public String[] getTokens(String csvString) {
StringBuffer sb = new StringBuffer(csvString);
String s [] = new String[getTokenCount(sb)];
int tc = 0;
int start = 0;
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == ',') {
s[tc] = sb.substring(start, i);
start = i + 1;
tc++;
}
}
s[tc] = sb.substring(start, sb.length());
return s;
}
/**
* This function calculates the number of values in the comma
* separated value string which is passed in as a parameter
* in the form of a StringBuffer object. Each character in the
* StringBuffer object is examined to determine whether or not
* it is a comma. If a comma is found, the count of tokens is
* incremented by one.
*/
public int getTokenCount(StringBuffer sb) {
int tc = 0;
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == ',')
tc++;
}
return tc + 1;
}
}