Java代码每次运行后settings配置文件内容自动清空问题求助
配置文件清空问题排查结果
核心原因
你在读写代码中同时实例化FileReader和FileWriter的逻辑存在致命错误:FileWriter无追加参数的构造方法默认是覆盖写入模式,只要你实例化new FileWriter(settingsFile)完成,不管后续是否执行写操作,文件原有内容会被立刻清空,之后你用FileReader读取的已经是被清空的空文件。
其他隐藏代码问题
- 变量作用域错误:
BufferedReader和BufferedWriter实例定义在try代码块内部,外部循环、写操作的代码无法访问,实际运行会直接报编译错误 - 目录创建逻辑错误:
mkdir()返回true仅代表目录首次创建成功,此时你调用directory.createNewFile()会把已经创建好的目录替换为同名普通文件,导致后续配置文件无法正常写入 - 空指针风险:硬编码循环读取6行,当配置文件行数不足时
readLine()会返回null,后续调用equals()方法会触发空指针异常 - 资源泄漏:未手动关闭IO流,可能导致写入内容滞留在缓冲区不会落盘,也会长期占用系统IO资源
修复方案
1. 修正目录与配置文件创建逻辑
File directory = new File(System.getProperty("user.home") + "\\Documents\\Messenger Server"); // 优先判断目录不存在再创建,mkdirs()支持递归创建多级目录,兼容性更好 if (!directory.exists()) { directory.mkdirs(); } File settingsFile = new File(directory, "settings.txt"); // 仅当配置文件不存在时才创建新文件 if (!settingsFile.exists()) { try { settingsFile.createNewFile(); System.out.println("Created Settings.txt"); System.out.println(settingsFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } }
2. 修正读写逻辑(先读后写,按需打开写流)
采用try-with-resources语法自动关闭IO流,避免资源泄漏:
ArrayList<String> settingList = new ArrayList<>(); // 第一步:先完整读取配置文件内容,此时不要打开写流 try (BufferedReader bf = new BufferedReader(new FileReader(settingsFile))) { String line; while ((line = bf.readLine()) != null) { settingList.add(line); } } catch (IOException e) { e.printStackTrace(); } // 第二步:校验配置是否需要修改 boolean needUpdate = false; if (settingList.isEmpty() || (!settingList.get(0).equals("alwaysOnTop=true") && !settingList.get(0).equals("alwaysOnTop=false")) { if (settingList.isEmpty()) { settingList.add("alwaysOnTop=false"); } else { settingList.set(0, "alwaysOnTop=false"); } needUpdate = true; } // 第三步:仅当需要修改时才打开写流,全量覆盖写入新配置 if (needUpdate) { try (BufferedWriter bw = new BufferedWriter(new FileWriter(settingsFile))) { for (String line : settingList) { bw.write(line); bw.newLine(); } } catch (IOException e) { e.printStackTrace(); } }
内容的提问来源于stack exchange,提问作者Monte Scott Barber
相关产品推荐
相关产品推荐

