如何从JTable读取多个对象并将其作为序列化对象存储到文本文件中
实现方案
核心问题说明
你当前代码只能存储单条数据的原因是:
writeData方法每次使用覆盖模式的文件输出流写入单个Examinee对象,旧数据会被新提交的内容直接覆盖readData方法仅读取单个对象并添加一行到JTable,无法加载多条历史数据
代码修改步骤
1. 前提确认
首先确保你的Examinee类已经实现了Serializable接口,否则无法正常序列化存储。
2. 修改writeData方法
改为先读取文件中已有的所有考生集合,追加新数据后整体写回,避免覆盖:
void writeData(Examinee newExaminee) throws IOException, ClassNotFoundException { List<Examinee> examineeList = new ArrayList<>(); File dataFile = new File(path); // 文件存在且不为空时先读取已有数据 if (dataFile.exists() && dataFile.length() > 0) { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFile)); examineeList = (List<Examinee>) ois.readObject(); ois.close(); } // 追加新提交的考生信息 examineeList.add(newExaminee); // 全量写回文件 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path)); oos.writeObject(examineeList); oos.close(); }
3. 修改readData方法
改为读取整个考生集合,遍历后全部添加到JTable中:
void readData() { // 先清空表格现有内容,避免重复加载 model.setRowCount(0); File dataFile = new File(path); if (!dataFile.exists() || dataFile.length() == 0) { return; } try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFile)); List<Examinee> examineeList = (List<Examinee>) ois.readObject(); ois.close(); // 遍历所有考生数据添加到表格 for (Examinee examinee : examineeList) { Object[] row = new Object[5]; row[0] = examinee.getFullName(); row[1] = examinee.getEmailAddress(); row[2] = examinee.getPassportNumber(); row[3] = examinee.getGender(); row[4] = examinee.getDob(); model.addRow(row); } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } }
4. 调整submit按钮的异常捕获
修改后的writeData会抛出ClassNotFoundException,需要调整catch块:
try { writeData(examinee); readData(); } catch (IOException | ClassNotFoundException e1) { e1.printStackTrace(); }
额外注意事项
- 需要提前导入
java.util.ArrayList、java.util.List、java.io.File三个依赖包 - 程序初始化时可主动调用一次
readData(),自动加载历史存储的所有考生数据到表格 - 序列化存储的文件为二进制格式,直接用文本编辑器打开会显示乱码,不影响程序正常读写,如需人可读的存储格式可调整为JSON序列化实现
内容的提问来源于stack exchange,提问作者s.rahman rahi
相关产品推荐
相关产品推荐

