I have some data that I am processing and then saving it in stringbuilder to be finally written to csv.
Currently, I am writing the entire stringBuilder at once using println
obtained as a result of processing some idData
array. But I want to write in batches so maybe let's say if the array data for ids has length = 200, I want to write 50 id's data at a time.
How can I do that?
Existing code of writing the entire string builder result
class A {
private StringBuilder sb;
public void appendBody(String[] idData) {
for(String id: idData) {
Data data = getData(id);
processData(data);
}
writeToCsv();
}
public void processData() {
.. processing that involves populating private property string builder
// adding some sample data here
this.sb.append("Name,Phone,Email\n");
this.sb.append("Glen,1234,glen@abcd.com\n");
this.sb.append("John,5678,john@efgh.com");
// end populating string builder
}
public String writeToCsv() throws DataNotFoundException {
String filename = "outputFileNamePath"; // sample filename, modified to be pasted here
PrintWriter writer;
try {
writer = new PrintWriter(new File(filename));
} catch (FileNotFoundException e) {
writeLog("ERROR", e.getMessage);
throw new Exception("Error while creating output file");
}
writer.println(this.sb.toString());
writer.close();
return filename;
}
}
Some suggestions and hints will be helpful.
P.S: Please don't comment on the log message or exception being rethrown or the name of the variables or any nitty gritties not related to my problem since they have been modified to add it here and pardon me for any mistakes in advance!