Sunday, October 25, 2009

Fixed Record file parser

/**
* This functions takes one line of fixed record file as sting and returns
* array of fields
*
* @author Kisor Biswal
* @param string
* @return
*/
private String[] splitter(String string) {
// Lets get the string by space
String[] subStrings = string.split(" ");
// Oh we have to consider the the spaces inside, Okay no problem we will
// joint these back
List finalResult = new ArrayList();
List tempStrings = new ArrayList();
boolean isFirst = false;
for (String s : subStrings) {
// Do the string contain double quote?
if (s.contains("\"")) {
// Yes, Lets check if first time
if (!isFirst) {
// Yes, add the sting to temp list and go ahead
tempStrings.add(s);
isFirst = true;
} else {
// No, Ok now time to concatenate all temp strings and
// append to final result list
tempStrings.add(s);
StringBuffer buffer = new StringBuffer();
for (String ts : tempStrings) {
buffer.append(ts);
// Put space back
if (!ts.endsWith("\"")) {
buffer.append(" ");
}
}
finalResult.add(buffer.toString().replace("\"", ""));
// Now just toggle the

isFirst = false;

}

} else if (isFirst) {
// Yes, add the sting to temp list and go ahead
tempStrings.add(s);
} else {
finalResult.add(s);
}

}
return finalResult.toArray(new String[finalResult.size()]);
}