首页 > 解决方案 > 同时读取和写入Java文件?

问题描述

我正在尝试以 json 格式读取 java 文件的内容并更新文件。我最初的计划是使用我需要的更新数据创建一个新的 json 对象,然后删除旧数据并将更新的内容附加到文件中。但是,我在同时读取和写入文件时遇到问题。我已经搜遍了,没有任何运气。请看下面。我在这里做的是逐行搜索文件中的用户名,然后获取键“余额”的值并将新存款添加到其中。但是,我似乎找不到写入文件的方法。

public static void depositAmount(){
    // Searching for user data
    String searchUser;
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter your username: ");
    searchUser = sc.nextLine();
    int deposit;
    StringBuilder sb = new StringBuilder();
    //Searching data for username and getting the deposit
    try
    {
        FileInputStream file = new FileInputStream("/Users/baidench/Documents/Github/Banking/banking.txt");
        Scanner scan = new Scanner(file);
        while(scan.hasNextLine())
        {
            final String line = scan.nextLine();
            if(line.contains(searchUser)){
                JSONObject customer = new JSONObject(line);
                int balance =  customer.getInt("balance");
                String name = customer.getString("fullName");
                System.out.println(name + ", your current balance is: " + balance);
                System.out.println("How much do you want to deposit? : ");
                deposit = sc.nextInt();
                customer.remove("balance");
                customer.put("balance", balance + deposit);
                JSONObject newCustomerData = customer;
                //sb.append(newCustomer);
                System.out.println(newCustomerData);

                //scan.close();

                //FileWriter filetoWrite = new FileWriter("/Users/baidench/Documents/Github/Banking/data.txt", true);
                //filetoWrite.write(sb + System.lineSeparator());
            }
        }
        scan.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

标签: javajsonfilesoftware-design

解决方案


在创建输出之前,您不要关闭FileInputStream总是必须关闭您的输入。

//More Code
  customer.remove("balance");
                customer.put("balance", balance + deposit);
                JSONObject newCustomerData = customer;

                //sb.append(newCustomer);

                System.out.println(newCustomerData);


                scan.close();

               //This.
                file.close();

                FileWriter filetoWrite = new FileWriter("/Users/baidench/Documents/Github/Banking/data.txt", true);
                filetoWrite.write(sb + System.lineSeparator());

//More code....
... 


推荐阅读