将文本框保存到文本文件并在文本框中加载文本文件内容(序列化)Java

3
我要做的是将文本框中的信息保存到文本文件中。加载文本文件时,文本框将被填充信息。在保存文件时,我遇到了一个异常错误,如下所示:Exception e.printStackTrace(); 感谢您的帮助。

 private void savecustButtonActionPerformed(java.awt.event.ActionEvent evt) {
     Customer customer = new Customer();
     try {
       FileOutputStream fos = new FileOutputStream("Customers/" + custidTF.getText() + ".txt");
       ObjectOutputStream oos = new ObjectOutputStream(fos);

       customer.setPersonName((custnameTF.getText()));
       customer.setPersonSurname((custsurnameTF.getText()));
       customer.setPersonID((custidTF.getText()));

       oos.writeObject(customer);
       oos.close();
     } catch (IOException e) {

     }

     dispose();

private void loadCustomerActionPerformed(java.awt.event.ActionEvent evt) {
  Customer customerfile = null;

  try {

    final JFileChooser chooser = new JFileChooser("Customers/");
    int chooserOption = chooser.showOpenDialog(null);
    chooserOption = JFileChooser.APPROVE_OPTION;

    File file = new File(chooser.getSelectedFile().getAbsolutePath());
    ObjectInputStream in = new ObjectInputStream(
      new FileInputStream(file)
    );

    customerfile = (Customer) in .readObject(); in .close();

  } catch (IOException ex) {
    System.out.println("Error loading file.");
  } catch (ClassNotFoundException ex) {
    System.out.println("Invalid class in loaded file.");
  }

}


你能从 IOException ex 中获取更多的信息吗? - Wai Ha Lee
无法加载文件。 - Luke_i
您可以从 IOException 中获取更多信息,例如使用 getMessage... - Wai Ha Lee
1
@Luke_i 请在save方法的catch部分添加e.printStackTrace();,并向我们展示结果。 - m.cekiera
1
@Luke_i,所以你的Customer类根本不可序列化,你无法保存和加载,我理解得对吗,你没有实现序列化? - m.cekiera
显示剩余5条评论
1个回答

1
我认为你的Customer类没有实现Serializable接口。在类开头语句中添加implements Serializable

我已经编辑了我的类并实现了Serializable接口,保存文件时没有出现错误:),但是文件仍然无法加载。谢谢 - Luke_i
如果您尝试从Customer customerfile的文本字段读取数据会发生什么? - m.cekiera
从客户customerfile文本字段读取数据是什么意思?在文本字段中编写的文本被保存到文本文件中,然后加载时会出现异常错误。我想要加载对象。 - Luke_i
经过测试,再次加载时没有出现任何错误。即使使用了e.printStackTrace();语句,文本框仍然保持为空。谢谢。 - Luke_i
但是指的是GUI中的文本框,还是客户文件中的字段? - m.cekiera
GUI文本框保持为空白,就像什么也没有发生一样。保存的文本文件无法读取,但输入的值在文件末尾,因此我认为保存正确。 - Luke_i

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接