Java写入txt文件无法追加内容每次生成新文件问题求解
问题根因
你当前代码存在两个核心问题导致无法追加写入同一文件:
- 文件名动态生成:每次调用
writeToFile方法时,都会拼接精确到秒的时间戳作为文件名的一部分,每次调用时间不同,自然每次生成独立的新文件,不会写入已有文件 - 未开启追加写入模式:
FileWriter默认构造方法为覆盖写入模式,就算文件名固定,每次写入也会清空原有文件内容,不会追加
解决方案
核心修改点
- 调整文件名规则:去掉文件名中精确到秒的时间戳,可根据需求选择固定文件名、或按天/小时等粗粒度时间分割文件名
- 开启
FileWriter追加模式:调用FileWriter构造方法时传入第二个参数true,开启追加写入
修改后完整代码
@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(); // 如果需要按天分割日志,时间格式保留到天即可,示例:ddMMyyyy SimpleDateFormat dateFormatForFileName = new SimpleDateFormat("ddMMyyyy"); SimpleDateFormat dateFormatForContent = new SimpleDateFormat("ddMMyyy_HHmmss"); // 固定文件名,按天分割则保留日期到天 String logFilePath = summaryLogsDbDir + LOGS_FILENAME + dateFormatForFileName.format(date) + ".txt"; // FileWriter第二个参数传true开启追加模式 try (BufferedWriter out = new BufferedWriter(new FileWriter(logFilePath, true))) { String timeStr = dateFormatForContent.format(date); out.append(timeStr + ": " + processName + "\n"); out.append(timeStr + ": " + activity + "\n"); out.append(timeStr + ": " + numberOfRecords + "\n"); // 可加分割线区分不同批次的日志 out.append("---\n"); } catch (Exception e) { throw new Exception("Failed to write summary log file.", e); } log.info("writeToFile has been executed!"); }
额外优化建议
SimpleDateFormat是线程不安全的,如果你的代码存在多线程调用场景,建议替换为java.time包下的DateTimeFormatter,避免并发安全问题- 如果存在多线程同时写日志的场景,建议对写入操作加锁,避免多线程写入导致的日志内容错乱、文件损坏问题
- 路径拼接建议使用
Paths.get(summaryLogsDbDir, LOGS_FILENAME + 后缀 + ".txt").toString(),避免不同操作系统的路径分隔符不兼容问题
内容的提问来源于stack exchange,提问作者user16750862
相关产品推荐
相关产品推荐

