應用程序應該能夠註冊一個新用戶並將數據保存到已經有很多用戶數據的文本文件中。此代碼是有效的,但它不會將新數據保存到文本文件。我應該如何覆蓋文本文件?我應該先從文本中讀取數據並將所有數據寫回到文本文件,還是有辦法添加新行並在其中寫入新數據?用Java覆蓋文本文件
registerB.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String getFullname = fullnameT.getText();
String getUsername = usernameT.getText();
String getPassword = passwordT.getText();
String getPN = pnT.getText();
String getEmail = emailT.getText();
boolean theSame = false;
String []Fullname = new String[20];
String []Username = new String[20];
String []Password = new String[20];
String []PN = new String[20];
String []Email = new String[20];
if(!getFullname.isEmpty() && !getUsername.isEmpty() && !getPassword.isEmpty() && !getPN.isEmpty() && !getEmail.isEmpty()){
int k = 0;
try {
Scanner in = new Scanner (new FileReader("login.txt", true));
while (in.hasNext()) {
Fullname[k] = in.next();
Username[k] = in.next();
Password[k] = in.next();
PN[k] = in.next();
Email[k] = in.next();
in.next();
if(getUsername.equals(Username[k])){
JOptionPane.showMessageDialog(null, "Username already has been registered.");
theSame = true;
break;
}
k++;
}
}catch(Exception ew){}
try
{
String path = "login.txt";
File file = new File(path);
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
fileWriter.append("," + getFullname + "," + getUsername + "," + getPassword + "," + getPN + "," + getEmail +"," + "\n");
bufferFileWriter.close();
System.out.println("User Registration Completed");
}catch(Exception ex){
System.out.println(ex);
}
else{
JOptionPane.showMessageDialog(null, "One or some of the fields is/are empty");
}
}
});
文本文件的格式是這樣的
fullname,username,password,phonenumber,email
fullname,username,password,phonenumber,email
可能重複(http://stackoverflow.com/questions/1625234/how-to-在java中添加文本到現有文件) – 2014-08-28 18:05:09