英文:
How to continue append the new record into text file without replace the old record (Java)
问题
我的问题是,当我添加新记录时,它会替换旧记录。
以下是将从文本框中获得的所有输入写入文本文件的代码块:
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);
}
这是主类:
Scanner lg = new Scanner(new File("LogFile.txt"));
while(lg.hasNext()){
lg.nextLine();
}
文本文件中的输出:
USERNAME ROLE ACTION LOGON_TIME
a Lecturer Login 21/August/2020 03:17:2
因此,如果我希望程序能够继续将新记录附加到文本文件中,我需要做什么解决方案?
英文:
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?
答案1
得分: 0
以追加模式打开文件。
通常情况下,打开一个文件会覆盖原始文件中的任何数据。然而,如果你使用带有文件名和布尔值true的FileOutputStream来打开文件,它会将新数据追加到原始数据之后。
FileOutputStream file = new FileOutputStream(String filename, boolean append)
要像最初打开一样打开PrintWriter,使用以下代码行:
PrintWriter p = new PrintWriter(new FileOutputStream("Logfile.txt", true));
然后你可以向文件中写入数据,新数据将会被追加到原始文件中。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论