2015-05-01 47 views
3

我在做的是將文本框中的信息保存到文本文件中。當文本文件被加載時,文本框將被填充信息。當保存文件時,我通過異常e.printStackTrace()得到這個錯誤;由於將文本框保存到文本文件並加載文本框中的文本文件內容(序列化)Java

enter image description here

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."); 
 
    } 
 

 
}

+0

你能從'IOException ex'得到更多的信息嗎? –

+0

不只是'錯誤加載文件' –

+0

您可以從['IOException'](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html)獲得更多信息,例如與'getMessage' ... –

回答

1

我認爲您的客戶類沒有實現Serializable接口。將implements Serializable添加到課堂開放式的講座中。

+0

我編輯我的類與實現Serializable和當保存文件我現在沒有錯誤:),但仍然沒有加載文件。謝謝 –

+0

如果您嘗試從Customer customer textfields中讀取數據,會發生什麼情況? –

+0

從客戶customerfile文本字段讀取數據是什麼意思?文本文件夾中的文本將被保存到文本文件中,而不是在加載它時發出「執行錯誤」。我想加載對象。 –

相關問題