Writing into a text file without overwriting existing content

Viewed 49

I have this current implementation but I couldn't append the new data that were being passed on in processName, activity and numberOfRecords. It just keeps creating a separate .txt file for each transaction.

    @Override
    public void saveSummaryLogs(String processName, String activity,
            int numberOfRecords) throws Exception {

        log.info("Test if this method is being executed.");
        log.info(INSERT_LOGS_TO_FILE);

        log.info("Creating a folder directory is being executed!");

         try {
             File f = new File(summaryLogsDbDir);
             f.mkdirs();
         }  catch (Exception e) {
            throw new Exception("Permission denied to create parent folder.",
                    e);
        }

         writeToFile(processName, activity, numberOfRecords);

         log.info("writeToFile has been called and executed!");
    }

    public void writeToFile(String processName, String activity,
                            int numberOfRecords) throws Exception {

        log.info("writeToFile is being executed!");

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyy_HHmmss");

        try (BufferedWriter out = new BufferedWriter(new FileWriter(
                summaryLogsDbDir + LOGS_FILENAME + dateFormat.format(date)
                        + ".txt"))) {
            out.append(dateFormat.format(date)+ ": " + processName + "\n");
            out.append(dateFormat.format(date)+ ": " + activity + "\n");
            out.append(dateFormat.format(date)+ ": " + numberOfRecords + "\n");
        } catch (Exception e) {
            throw new Exception("Failed a summary-logs.txt file.", e);
        }

        log.info("writeToFile has been executed!");
    }

Any help of advise is greatly appreciated. Thanks!

0 Answers
Related