I am creating a daily savings log application.
the files I am using overwrites existing data. I need a solution in which the files can be updated without overwriting existing data.
Here's the code I'm working on;
for writing the data:
private static void write(int cur_bal,int amt ,int flag) throws IOException
{
File file = new File("bal.txt");
log= new BufferedWriter(new FileWriter("log.txt"));//writer for log
bal= new BufferedWriter(new FileWriter(file));// " " bal
Scanner File = new Scanner(file);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String stat ="";
int balance=0;
switch(flag)
{
case 1:
{stat="Added";
balance = cur_bal+amt;
break;}
case 2:
{stat="Removed";
balance = cur_bal-amt;
break;}
}
String inf=sdf.format(date)+" "+amt+" ("+stat+")";
System.out.println(inf);
System.out.println(balance);
bal.write(balance+"\n");
log.write(inf+"\n");
bal.close();
log.close();
}
for reading the file:
private static int bal_read() throws IOException
{
FileReader fr=new FileReader("bal.txt");
int i,balance=0;
while((i=fr.read())!=-1)
balance = i;
fr.close();
return (balance);
}
如果 FileWriter 是以追加模式创建的,则 BufferedWriter 可以追加到文件中: new FileWriter(file, true)
One solution -
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("file.txt", true)));
pw.println("some text");
pw.close();
Another way is to create new FileWriter(file, true) - The second parameter true enables append mode.
However you should use logging frameworks like Log4j for maintaining logs.
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.