简体   繁体   English

如何将GUI中的数据保存到文本文件(java)

[英]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.我试图将数据(用户将在 TextField 中输入)保存到文本文件中。 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.我猜你的 FileWriter 声明不正确。 Never set variable names same as the target class name.切勿将变量名称设置为与目标 class 名称相同的名称。 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.并且下次当您提出问题时,请提供异常消息,这将有助于回答问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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