简体   繁体   中英

How to continue append the new record into text file without replace the old record (Java)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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