Below code is used to write HotelReportModel data into csv file. I am planning to replace try with try-with-resources Statement but how should i handle filewritter.flush?. which is inside finally block.
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(tempCSVFilePath);
fileWriter.append(hotelReportModel.getHeader());
fileWriter.append(NEW_LINE_SEPARATOR);
for(HotelReportModel imageStat:hotelReportModel.getContent()){
fileWriter.append(imageStat.getMarketerName());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(imageStat.getChainCode());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(imageStat.getPropertyId());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(imageStat.getContentProvider());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(String.valueOf(imageStat.getPropertyImageCount()));
fileWriter.append(NEW_LINE_SEPARATOR);
}
LOGGER.info("CSV file was created successfully !!!");
} catch (Exception e) {
LOGGER.error("Error in CsvFileWriter !!!",e);
} finally {
try {
if(fileWriter != null) {
fileWriter.flush();
fileWriter.close();
}
} catch (IOException e) {
LOGGER.error("Error while flushing/closing fileWriter !!!",e);
}
}
Is below try with resource is right?
try(FileWriter fileWriter = = new FileWriter(tempCSVFilePath) ) {
fileWriter.append(hotelReportModel.getHeader());
fileWriter.append(NEW_LINE_SEPARATOR);
for(HotelReportModel imageStat:hotelReportModel.getContent()){
fileWriter.append(imageStat.getMarketerName());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(imageStat.getChainCode());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(imageStat.getPropertyId());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(imageStat.getContentProvider());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(String.valueOf(imageStat.getPropertyImageCount()));
fileWriter.append(NEW_LINE_SEPARATOR);
}
LOGGER.info("CSV file was created successfully !!!");
} catch (Exception e) {
LOGGER.error("Error in CsvFileWriter !!!",e);
}
}
You don't need to worry about that, as you're calling
close
(from the javadoc):(Their example used a
BufferedReader
, but that doesn't matter, as bothBufferedReader
andFileWriter
implementAutoCloseable
).So simply using
try with resources
will both close and flush thefileWriter
.