java - 同时读取和写入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();
}
}
解决方案
在创建输出之前,您不要关闭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....
...
推荐阅读
- api - 在 tcl 包过程中调用 TCL C API
- php - 带有 \n 的字符串导致以下变量错误
- python - 如何使用单个字母字符串列表作为输入生成概率最高的二元组结果
- sails.js - Sails.JS 温斯顿总是以 JSON 格式显示?
- python - 使用 != 运算符在 Python 中删除行不起作用
- javascript - 使用rails注销用户后如何清除localStorage?
- javascript - ChartJS:自定义图例不显示多饼图的标签
- reactjs - TypeError:无法设置未定义的属性“setState”。反应
- python-3.x - Python 看门狗模块重复事件(编辑:不是看门狗问题)
- c# - 尽管 byte[] 包含有效的图像数据,但绑定的图像不会呈现