【发布时间】:2018-05-05 11:52:31
【问题描述】:
那么,问题来了。我想使用 java GUI 创建一个文件,这就像用户可以在我的 GUI 中创建一个帐户或登录,然后他们的帐户变成我的 file.txt。但是,我这里有个问题。当我在我的 GUI 中创建一个帐户时,它运行良好,并且创建了文件。但是,当我再次尝试创建帐户时,之前创建的帐户消失了。所以,我想在这种情况下我需要使用arraylist,并且我使用它,但它仍然不起作用。这是代码:
String filename="D:/settings.txt";
public void getIdentity() throws FileNotFoundException, IOException{
File file = new File(filename);
ArrayList identity = new ArrayList();
String fullname = txt_fullname.getText();
String username = txt_username.getText();
String password = pass_password.getText();
try {
FileWriter fw = new FileWriter(filename);
Writer output = new BufferedWriter(fw);
identity.add(fullname + "-" + username + "-" + password);
for (int i = 0; i <identity.size(); i++)
{
output.write(identity.get(i).toString() + "\n");
}
output.close();
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Cannot create a file");
}
}
这就是行动:
try {
if(txt_username.getText() != null && pass_password.getText() != null
&& txt_fullname.getText() != null)
{
getIdentity();
JOptionPane.showMessageDialog(null, "Congratulations, you've created a file");
this.setVisible(false);
Login login = new Login();
login.setVisible(true);
}
else {
JOptionPane.showMessageDialog(null, "Please fill in your identity");
}
} catch (IOException ex) {
}
【问题讨论】:
-
如果此答案适合您,请将答案标记为“已接受”。
标签: java arraylist file-io fileinputstream