求助:Java序列化报错java.io.WriteAbortedException,无法序列化FileOutputStream
问题排查与解决
核心错误原因
你当前代码的问题在于错误地尝试序列化并写入FileOutputStream对象:
output.writeObject(file);
FileOutputStream类并未实现Serializable接口,因此序列化时会抛出NotSerializableException,进而引发WriteAbortedException。更关键的是,你的真实需求是保存表格数据(tableData),而非文件输出流对象。
修正后的代码
基础修正版
直接将写入对象替换为表格数据tableData:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); Vector<Vector> tableData = model.getDataVector(); //Saving of object in a file try { FileOutputStream file = new FileOutputStream("StudentFile.bin"); ObjectOutputStream output = new ObjectOutputStream(file); // 写入表格数据而非FileOutputStream对象 output.writeObject(tableData); output.close(); file.close(); } catch (Exception ex) { ex.printStackTrace(); } new ComputerScience_IA_UI().setVisible(true); this.dispose();//to close the current jframe }
优化版(使用try-with-resources自动管理流)
推荐使用Java的try-with-resources语法,无需手动关闭流,避免资源泄漏:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); Vector<Vector> tableData = model.getDataVector(); // 使用try-with-resources自动关闭流 try (FileOutputStream file = new FileOutputStream("StudentFile.bin"); ObjectOutputStream output = new ObjectOutputStream(file)) { output.writeObject(tableData); } catch (Exception ex) { ex.printStackTrace(); } new ComputerScience_IA_UI().setVisible(true); this.dispose(); }
额外注意事项
如果表格中存储的是自定义对象(而非字符串、数字等基本类型包装类),需要确保该自定义类实现Serializable接口,否则仍会抛出序列化异常。例如:
// 自定义学生类示例 public class Student implements Serializable { private String name; private int age; // 构造方法、getter/setter等 }
内容的提问来源于stack exchange,提问作者Pablo Ducharne
相关产品推荐
相关产品推荐

