Java程序无法读取output.txt致去重失效,求技术分析
问题原因分析
1. 文件初始化时的清空操作
你在main方法中使用PrintWriter writer = new PrintWriter("output.txt");初始化输出流时,这个操作会立即清空output.txt的所有内容,并且将文件保持在写入锁定状态。后续调用doesExist方法读取该文件时,只能读到空内容,导致判断逻辑永远返回false,所有输入行都会被重复写入。
2. 读写流冲突
当output.txt被PrintWriter以写入模式占用时,同一文件无法被FileReader正常读取(部分操作系统会对写入中的文件加锁),即使你调用flush(),未关闭的写流也会导致读流无法获取完整的文件内容。
3. 逻辑执行顺序错误
在处理输入行的循环中,你先打开了output的写流,但直到循环结束才flush和关闭,这导致在循环过程中,doesExist读取的始终是初始为空的文件,完全无法检测到已经写入的内容。
修复方案
修正后的代码
import java.io.*; class Merge { public static boolean doesExist(String mobileNo) { // 用try-with-resources自动关闭流,避免资源泄漏 try (BufferedReader reader = new BufferedReader(new FileReader("output.txt"))) { String existLine; while ((existLine = reader.readLine()) != null) { if (existLine.equals(mobileNo)) { return true; } } } catch (FileNotFoundException e) { // 文件不存在,说明当前数字未被写入过 return false; } catch (IOException e) { e.printStackTrace(); } return false; } public static void main(String[] args) throws IOException { BufferedReader inputReader = new BufferedReader(new FileReader("input.txt")); String mobileNo = inputReader.readLine(); while (mobileNo != null) { if (!doesExist(mobileNo)) { // 以追加模式打开输出流,避免清空已有内容 try (PrintWriter writer = new PrintWriter(new FileWriter("output.txt", true))) { writer.println(mobileNo); } } mobileNo = inputReader.readLine(); } inputReader.close(); } }
关键改动说明
- 移除了提前打开的全局写流,改为每次需要写入时以追加模式打开,避免清空文件和读写冲突。
- 使用
try-with-resources语法自动关闭流,避免资源泄漏。 - 处理
doesExist中的FileNotFoundException,适配output.txt初始不存在的场景。 - 去掉了无用的
import java.util.*。
内容的提问来源于stack exchange,提问作者Suraj Kumar Sahani
相关产品推荐
相关产品推荐

