简体   繁体   English

从 Java 中的文本文件替换字符串

[英]Replacing a string from text file in Java

I've got a text file like this: https://i.stack.imgur.com/nL0Z4.png The first column represents the user ID and the last column represents balance.我有一个这样的文本文件: https://i.stack.imgur.com/nL0Z4.png第一列代表用户 ID,最后一列代表余额。 I want to iterate through the elements to find a specific user ID and then update their balance.我想遍历元素以找到特定的用户 ID,然后更新他们的余额。 I've managed to match the user ID and access the balance using the Scanner but I'm not sure how to update the balance in the text file with a new value.我已经设法匹配用户 ID 并使用扫描仪访问余额,但我不确定如何使用新值更新文本文件中的余额。 This is the code I've written so far: I tried to take the elements, modify the balances and put the updated values in an arraylist.这是我到目前为止编写的代码:我尝试获取元素,修改余额并将更新的值放入 arraylist 中。 Then put them into the text file using PrintWriter.然后使用 PrintWriter 将它们放入文本文件中。 But I keep getting an empty text file when I call this function.但是当我调用这个 function 时,我总是得到一个空的文本文件。

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();

I would highly reccomend to use Serialization for this.我强烈建议为此使用序列化。 I am assumming you already have a Customer class with balance,id etc. With Serialization things are just as simple as getting the customer you want,updating his balance,and then writing in your file.For example:我假设你已经有一个Customer class balance,id等。通过序列化,事情就像获取你想要的客户一样简单,更新他的余额,然后写在你的文件中。例如:

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

And the write method would look like this写方法看起来像这样

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();
        }
    }

More on Serialization here更多关于序列化here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM