I am processing a file as the following and closing it. Later, I do some more processing and get some ID that I want to append to all rows in the previous CSV generated. So all rows will have the same value.
My initial code of creating and appending data to csv:
private StringBuilder stringBuilder = new StringBuilder();
public void writeToFile(String[] tIds, PrintWriter printWriter) throws DataNotFoundException {
int rowCount = 0;
for(String id: tIds) {
Data data = util.getData(id);
csvHelper.prepareFileData(data, this.stringBuilder);
rowCount++;
if (rowCount == CHUNK_SIZE) {
printWriter.println(this.stringBuilder.toString());
this.stringBuilder = new StringBuilder();
rowCount = 0;
}
}
printWriter.close();
}
Now further processing returns me some processedID
that I want to append to all rows as a new column.
One option is this:
public void appendAgain(String processedId) {
BufferedReader br = new BufferedReader(new FileReader(feedFile));
String output = "";
String line;
while ((line = br.readLine()) != null) {
output += line.replace(",", "," + alertId + ",");
}
FileWriter fw = new FileWriter(feedFile, false); //false to replace file contents, your code has true for append to file contents
fw.write(output);
fw.flush();
fw.close();
}
public void prepareFileForData(Data data, StringBuilder sb) {
// map values from data to sb
sb.append(data.getId());
sb.append(",");
sb.append(data.getName());
.. and so on
}
Please comment on a better way or any suggestions on the current one. Thanks!