尝试使用资源如何调用flush方法

时间:2016-12-20 13:38:29

标签: java collections try-catch file-handling

下面的代码用于将HotelReportModel数据写入csv文件。我打算用try-with-resources语句替换try,但我该如何处理filewritter.flush?。这是最后一块。

       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);
        }
    }

以下尝试用资源是对的吗?

         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);
    } 
    }

1 个答案:

答案 0 :(得分:4)

您无需担心,因为您正在呼叫close(来自javadoc):

  

因为在try-with-resource语句中声明了BufferedReader,所以无论try语句是正常还是突然完成,它都将被关闭。

(他们的示例使用了BufferedReader,但这并不重要,因为BufferedReaderFileWriter都实现了AutoCloseable。)

因此,只需使用try with resources即可关闭并刷新fileWriter