简体   繁体   中英

How to save the data in the GUI to the text file (java)

I tried to save the data (that the user will enter in the TextField) to the textfile. However it will only says error.

By the way this is my code.

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

I am guessing that your FileWriter declaration is incorrect. Never set variable names same as the target class name. Always aim to use lower case letters for variables. Therefore:

FileWriter Writer = new FileWriter("admin.txt");

should be written like this:

FileWriter writer = new FileWriter("admin.txt");

Afterwards, you call methods like this:

writer.write(someString);
writer.flush();
writer.close();

These two are the most important:

writer.flush();
writer.close(); 

And next time when you ask a question, please provide the Exception message, it will help when answering the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM