[英]How to save the data in the GUI to the text file (java)
我試圖將數據(用戶將在 TextField 中輸入)保存到文本文件中。 但是它只會說錯誤。
順便說一句,這是我的代碼。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String name = jTextField1.getText();
String age = jTextField2.getText();
String sex = jTextField3.getText();
String status = (String)jComboBox1.getSelectedItem().toString();
String address = jTextField4.getText();
String contactNum = jTextField5.getText();
String emailAdd = jTextField6.getText();
String userName = jTextField7.getText();
String password = jTextField8.getText();
try
{
FileWriter Writer = new FileWriter("admin.txt");
Writer.write("Name: " + name + " Age: " + age + " Sex: " +
sex + " Status: " + status + " Address: " + address +
" Contact # : " + contactNum + " Email Add.: " + emailAdd +
" Username: " + userName + " Password: " + password);
Writer.write(System.getProperty("line.seperator"));
Writer.close();
JOptionPane.showMessageDialog(rootPane, "Admin account was created successfully");
setVisible(false);
new frontpage().setVisible(false);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(rootPane, "Error!");
}
}
我猜你的 FileWriter 聲明不正確。 切勿將變量名稱設置為與目標 class 名稱相同的名稱。 始終旨在為變量使用小寫字母。 所以:
FileWriter Writer = new FileWriter("admin.txt");
應該這樣寫:
FileWriter writer = new FileWriter("admin.txt");
之后,你調用這樣的方法:
writer.write(someString);
writer.flush();
writer.close();
這兩個是最重要的:
writer.flush();
writer.close();
並且下次當您提出問題時,請提供異常消息,這將有助於回答問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.