My problem now is when I append the new record, it will replace the old one.
Below is the block of code which write all the input I get from the textbox to the text file:
try{
PrintWriter p = new PrintWriter("LogFile.txt");
p.print("USERNAME\tROLE\t\tACTION\t\tLOGON_TIME\n");
p.print(AcademicSystem.user.getLogin_username() + "\t\t");
p.print(AcademicSystem.user.getRole()+ "\t");
p.print("Login" + "\t\t");
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s");
p.print(simpleformat.format(cal.getTime())+ "\n");
p.println();
p.close();
}catch(Exception er){
JOptionPane.showMessageDialog(this,er);
}
This is the main class:
Scanner lg = new Scanner(new File("LogFile.txt"));
while(lg.hasNext()){
lg.nextLine();
Output in the text file:
USERNAME ROLE ACTION LOGON_TIME
a Lecturer Login 21/August/2020 03:17:2
Thus, what isthe solution which I need to do, if I want the program is able to continue append the new record to the text file?
Open the file in append mode.
Normally opening a file overwrites whatever data there was in the original file. However, if you open a FileOutputStream with a filename and a boolean of true, it will append the new data after the original data.
FileOutputStream file = new FileOutputStream(String filename, boolean append)
To open the PrintWriter like it was originally opened, use the line:
PrintWriter p = new PrintWriter(new FileOutputStream("Logfile.txt", true));
Then you can write to the file and new data will be appended to the original file.