Java电话目录项目中JTextField输入无法写入FileWriter问题求解
问题根因
你写入失败的核心原因是BufferedWriter缓冲流使用后没有手动刷新/关闭资源,写入的内容还停留在JVM内存缓冲区中,没有真正同步到磁盘文件。
修复方案
1. 新增流关闭/刷新逻辑
在case1的写入代码完成后,主动调用close()方法关闭缓冲流,关闭前会自动触发缓冲区刷新,把内容写入文件:
if (add == JOptionPane.OK_OPTION) { String student1 = student.getText(); String name1 = name.getText(); String address1 = address.getText(); String phone1 = phone.getText(); FileWriter fw = new FileWriter(new File("directory.txt"), true); BufferedWriter out = new BufferedWriter(fw); out.write(student1 + " " + name1 + " " + address1 + " " + phone1); out.newLine(); // 新增以下两行代码即可完成写入 out.close(); fw.close(); }
更规范的写法是用try-with-resources自动管理流资源,不需要手动关流,还能自动捕获IO异常:
if (add == JOptionPane.OK_OPTION) { String student1 = student.getText(); String name1 = name.getText(); String address1 = address.getText(); String phone1 = phone.getText(); // try-with-resources语法会在代码块执行结束后自动关闭流 try (BufferedWriter out = new BufferedWriter(new FileWriter("directory.txt", true))) { out.write(student1 + " " + name1 + " " + address1 + " " + phone1); out.newLine(); } catch (IOException e) { // 不要留空catch块,打印报错方便排查问题 e.printStackTrace(); JOptionPane.showMessageDialog(null, "保存失败:" + e.getMessage()); } }
2. 其他潜在问题修复
- 你代码中定义的
quit变量没有实际使用,需要新增case5的退出逻辑,否则程序会一直循环:
case 5: quit = true; break;
- 目前你用空格分割字段,如果用户输入的地址、姓名里包含空格,搜索时split会抛出数组越界异常,建议改用
\t制表符或者其他用户不会输入的特殊分隔符存储和分割数据。 - 搜索逻辑的空catch块建议补上异常打印,避免文件不存在、读取出错时完全没有反馈。
内容的提问来源于stack exchange,提问作者raphael ungab
相关产品推荐
相关产品推荐

