如何在不覆盖现有数据的情况下添加数据?

How to add data without overwriting the existing 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();
    }

读取文件:

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)

一个解决方案-

PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("file.txt", true)));
pw.println("some text");
pw.close();

另一种方法是创建新的 FileWriter(file, true) - 第二个参数 true 启用追加模式。

但是,您应该使用 Log4j 等日志记录框架来维护日志。