The application should be able to register a new user and save data to text file which is already has many users' data. This code is works but it doesn't save new data to text file. How should I overwrite the text file? Should I read data from text first and write all the data back to text file or there is a way to just add a new line and write new data there?
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");
}
}
});
The text file format is like this
fullname,username,password,phonenumber,email
fullname,username,password,phonenumber,email