JSONArray dataRows = new JSONArray();
while (scanner.hasNextLine()) {
// Check for the header row
if (rowCount + 1 == headerRowIndex) {
String line = scanner.nextLine();
CSVReader reader = new CSVReader(new StringReader(line),
delimiter, quoteCharacter, escapeCharacter);
String[] rowValues = reader.readNext();
List<String> headers = new ArrayList<String>();
if (rowValues == null || rowValues.length == 0) {
logger.error("No data found in the Header row!");
rowCount++;
scanner.nextLine();
continue;
}
for (int i = 0; i < rowValues.length; i++) {
headers.add(rowValues[i]);
}
// Add the row index
headers.add(0, Integer.toString(rowCount + 1));
// Add to the output JSON
JSONArray arr = new JSONArray(headers);
writer.key(JsonKeys.headers.name()).value(arr);
rowCount++;
reader.close();
continue;
}
// Check for the data rows. We choose the first five for preview
if (rowCount + 1 >= dataStartRowIndex
&& rowCount + 1 < dataStartRowIndex + 5) {
if (previewRowCounter++ > 5) {
break;
}
String line = scanner.nextLine();
CSVReader reader = new CSVReader(new StringReader(line),
delimiter, quoteCharacter, escapeCharacter);
String[] rowValues = reader.readNext();
List<String> vals = new ArrayList<String>();
if (rowValues != null) {
for (int i = 0; i < rowValues.length; i++) {
vals.add(rowValues[i]);
}
} else
vals.add("");
// Add the row index
vals.add(0, Integer.toString(rowCount + 1));
reader.close();
// Add to the data rows JSON
dataRows.put(vals);
rowCount++;
continue;