在java中更新文本文件的特定部分 [英] Updating a specific portion of a text file in java

查看:103
本文介绍了在java中更新文本文件的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我需要在每次用户提取时更新文本文件的Balance列。我使用了write方法和append方法,但无济于事。
用户登录后,该特定行存储在数组中

In my program I need to update the Balance column of the text file each time the user does a withdrawal. I used both the write methods as well as the append methods, but to no avail. Once the user has logged in, that particular line is stored in the array

#PIN AccountNo Balance
1598 01-10-102203-0 95000
4895 01-10-102248-0 45000
9512 01-10-102215-0 125000
6125 01-10-102248 85000

代码:

try{
    BufferedWriter out = new BufferedWriter(new FileWriter(".\\AccountInfo.txt",true));
    if (amount <= 0.0) {
        System.out.println("can only withdraw positive amount!");
        transactionScreen();
    }
    else if (this.balance >= amount) {
        if(amount>15000.0){
            System.out.println("The maximum amount allowed per transaction is only Rs.15000/=");
            transactionScreen();
        }
        else{
            this.balance -= amount;
            object.c=this.balance;
            String newBal=Double.toString(this.balance);
            out.write("");
            //out.append("");
            out.write(newBal);
            //out.append(newBal);
        }
    }
    else {
        System.out.println("not enough money in account!");
        transactionScreen();
    }
}
catch(IOException e){
    e.printStackTrace();
}


推荐答案

唯一简单的方法这是每次进行任何更改时重写文本文件的全部内容。但由于以下几个原因,这很可怕:

The only simple way to do this is to rewrite the entire contents of the text file every time you make any change. But this is awful for several reasons:


  • 这是非常慢的。

  • 它只能是由一个线程一次完成,因此不易扩展。

  • 如果您的应用程序在写入期间崩溃,您可能会丢失所有数据。

您可以使用固定宽度列来搜索和写入文件而无需重写整个文件,但仍然存在问题:

You can use fixed width columns to allow seeking and writing into your file without having to rewrite the entire file, but there are still problems:


  • 如果您需要存储超出列所需宽度的值,则表示您遇到问题。

  • 您仍需要阅读整个文件(最坏情况 - 平均一半)找到你想要修改的记录(在内存中保留一个缓存会有帮助)。

我建议你改用数据库。有些数据库可以在本地安装,不需要管理(例如, SQLite )。

I'd suggest that you use a database instead. There are databases that you can install locally and require no administation (SQLite for example).

这篇关于在java中更新文本文件的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆