使用BufferedWriter/Reader实现文件行数统计与追加写入需求
解决文件追加行数统计的问题
我太懂这种卡壳的感觉了!流操作的顺序、模式稍微错一点,结果就完全不对。你已经搞定了条件行写入,剩下的行数追加其实核心就是处理好流的生命周期和文件打开模式,我给你拆解一下问题和解决方案:
常见踩坑点
你之前尝试的方法没成功,大概率是这几个原因:
- 第一次写文件B用了覆盖模式,之后追加时没切换成
append=true,导致把之前的内容覆盖了 - 写完条件行后没刷新/关闭流,缓冲区的内容还没写到磁盘,后续追加的内容跑到了文件开头
- 统计B的行数时机不对:比如写完条件行后直接读B统计,但此时流还没关闭,读不到最新的内容
最优解决方案:同一个流完成所有操作
其实不用搞多个BufferedWriter或者try块,写完符合条件的行后,直接在同一个流里追加统计信息就行——因为此时流的指针就在文件末尾,直接写就完事了,代码更简洁也不容易出错:
import java.io.*; public class FileProcessor { public static void main(String[] args) { String fileA = "A.txt"; String fileB = "B.txt"; // 第一步:先统计文件A的总行数 int totalLinesA = 0; try (BufferedReader brA = new BufferedReader(new FileReader(fileA))) { while (brA.readLine() != null) { totalLinesA++; } } catch (IOException e) { e.printStackTrace(); return; } // 第二步:写入符合条件的行到B,同时统计写入行数,最后追加统计信息 int totalLinesB = 0; try (BufferedWriter bwB = new BufferedWriter(new FileWriter(fileB)); BufferedReader brA = new BufferedReader(new FileReader(fileA))) { String line; while ((line = brA.readLine()) != null) { // 替换成你的条件判断,比如 line.contains("指定关键词") if (yourCustomCondition(line)) { bwB.write(line); bwB.newLine(); totalLinesB++; // 实时统计写入B的行数 } } // 直接在同一个流里追加统计信息 bwB.newLine(); bwB.write("文件A总行数: " + totalLinesA); bwB.newLine(); bwB.write("文件B总行数(不含统计行): " + totalLinesB); } catch (IOException e) { e.printStackTrace(); } } // 自定义条件判断方法,替换成你的逻辑 private static boolean yourCustomCondition(String line) { return line.trim().length() > 0; // 示例:非空行 } }
备选方案:分两次写入(先写条件行,再追加统计)
如果你一定要分开操作,那必须注意两个关键点:
- 第一次写B的流必须完全关闭(用try-with-resources自动处理)
- 第二次打开B时要用追加模式(
FileWriter(fileB, true))
代码示例:
// 第一步:写入符合条件的行到B,统计行数 int totalLinesB = 0; try (BufferedWriter bwB = new BufferedWriter(new FileWriter(fileB)); BufferedReader brA = new BufferedReader(new FileReader(fileA))) { String line; while ((line = brA.readLine()) != null) { if (yourCustomCondition(line)) { bwB.write(line); bwB.newLine(); totalLinesB++; } } } catch (IOException e) { e.printStackTrace(); } // 第二步:追加统计信息到B末尾 try (BufferedWriter bwAppend = new BufferedWriter(new FileWriter(fileB, true))) { bwAppend.newLine(); bwAppend.write("文件A总行数: " + totalLinesA); bwAppend.newLine(); bwAppend.write("文件B总行数(不含统计行): " + totalLinesB); } catch (IOException e) { e.printStackTrace(); }
核心注意事项
- 统计A的行数要提前完成,或者在处理A的时候同时统计(分开统计更清晰)
- 统计B的行数最好在写入时实时计数,不要事后再读B统计——因为流没关闭时文件内容可能还在缓冲区,读出来的行数不对
- 永远用
try-with-resources来管理流,它会自动帮你关闭流、刷新缓冲区,避免资源泄漏和数据丢失
内容的提问来源于stack exchange,提问作者romanzdk
相关产品推荐
相关产品推荐

