【问题标题】:Replacing a string from text file in Java从Java中的文本文件替换字符串
【发布时间】:2022-01-08 09:15:37
【问题描述】:

我有一个这样的文本文件:https://i.stack.imgur.com/nL0Z4.png 第一列代表用户 ID,最后一列代表余额。我想遍历元素以找到特定的用户 ID,然后更新他们的余额。我已经设法匹配用户 ID 并使用扫描仪访问余额,但我不确定如何使用新值更新文本文件中的余额。这是我到目前为止编写的代码:我尝试获取元素,修改余额并将更新的值放入数组列表中。然后使用 PrintWriter 将它们放入文本文件中。但是当我调用这个函数时,我总是得到一个空的文本文件。

File file = new File("UserInfo.txt");
Scanner sc = new Scanner(file);
ArrayList<String> items = new ArrayList<String>(); 
while(sc.hasNextLine()){
    String info = sc.nextLine();
    String data[] = info.split(" ");
    
    if(String.valueOf(currentUser.getAccountNumber()).equals(data[0])){
        data[3] = String.valueOf(currentUser.getBorrowBalance()); 
        //Updating the balance in ArrayList
    }else{
        continue;
    }
    for(int i=0; i<data.length; i++){
        items.add(data[i]);
    }
}
PrintWriter pw = new PrintWriter(file);
for(int j=0; j<items.size(); j++) {
    pw.printf("%s ", items.get(j));
    if(j%3==0) pw.println(); //Going to new line after writing 4 elements to text file
}
pw.close();
sc.close();

【问题讨论】:

    标签: java file arraylist file-io printwriter


    【解决方案1】:

    我强烈建议为此使用序列化。我假设你已经有一个 Customer 类和 balance,id 等。通过序列化,事情就像得到你想要的客户一样简单,更新他的余额,然后写在你的文件中。例如:

    customer = getCustomerById(selectedId);
    customer.setBalance(newBalance);
    customer.write();
    

    而 write 方法看起来像这样

    public void write(String filename) {
            try {
                File temp = new File(filename);
                temp.createNewFile(); // create file if not present
                FileOutputStream fileOut = new FileOutputStream(filename);
                ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
                objectOut.writeObject(this);
                
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    

    更多关于序列化here

    【讨论】:

      猜你喜欢
      • 2011-06-30
      • 1970-01-01
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多