如何使用java更改从文本文件读取的行内的值?

时间:2014-01-19 23:16:15

标签: java file text text-files edit

我有一个包含以下内容的文本文件:

12345678,1234,100,DefaultUser

第三个值“100”是货币余额,我需要帮助的是创建一个根据用户输入改变该值的退出方法。

有人可以展示一个这样的例子,所以我可以看到它是如何做到的? 这就是我所拥有的,我可能会离开。

//Withdraw
public static void withdraw(){
    //Create a scanner object
    Scanner sc = new Scanner(System.in);

    // Get user input
    System.out.println("How much money would you like to withdraw?\n");
    System.out.print("Enter amount:\t");
    float amount = sc.nextInt();

    try {
        BufferedReader br = new BufferedReader(new FileReader("Data/users.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("Data/users.txt"));
        String[] userInfo = br.readLine().split(",");

        float currBalance = Integer.parseInt(userInfo[2]);
        float newBalance = currBalance - amount;

        userInfo[2] = ""+newBalance;
        bw.write(userInfo+"");

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

以下示例是您尝试实现的非常粗略的版本。请注意,在完全重写文件以包含新值之前,代码会将文件的所有行放入Collection进行临时存储。

这允许单独读取和写入文件。

public class Withdrawl {

    public static void main(String[] args) throws IOException {

        Scanner sc = new Scanner(System.in);

        // Get user input
        System.out.println("How much money would you like to withdraw?\n");
        System.out.print("Enter amount:\t");
        float amount = sc.nextInt();

        File input = new File("Data/users.txt");

        BufferedReader br = new BufferedReader(new FileReader(input));
        List<String> lines = new LinkedList<String>();

        //Write all lines to a Collection
        String line;
        while((line = br.readLine()) != null){
            lines.add(line);
        }
        br.close();

        //This could would need to find the actual user instead of using hardcoded 2
        String[] tokens = lines.get(0).split(",");
        float currentBalance = Float.parseFloat(tokens[2]);
        float newBalance = currentBalance + amount;
        tokens[2] = String.valueOf(newBalance);

        String finalString = "";
        String comma = "";
        for(String s: tokens){
            finalString += comma + s;
            comma = ",";
        }

        lines.set(0, finalString);

        FileWriter fw = new FileWriter(input);
        for(String out:lines){
            fw.write(out);
        }
        fw.flush();
        fw.close();

    }
}