Home > OS >  Replacing a specific string from a text file in Java
Replacing a specific string from a text file in Java

Time:01-08

I've got a text file like this: Image

The first column represents the user ID and the last column represents balance. I want to iterate through the elements to find a specific user ID and then update their balance. 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. This is the code I've written so far:

        File file = new File("UserInfo.txt");
        Scanner sc = new Scanner(file);
        
        while(sc.hasNextLine()){
            String info = sc.nextLine();
            String data[] = info.split(" ");
            //userId is a function argument
            if(String.valueOf(userId).equals(data[0])){
               //I want to update the balance in the text file with a new value here
            }else{
                continue;
            }
        }
        sc.close();

CodePudding user response:

it seems that you want to create a CSV file. My advice is to use ";" as a separator for the split() command, and if the file is not too big, read the whole file, put it into an arrayList of Strings and then manipulate It, rewriting the whole file at the end from the arrayList. Otherwise you have to use RandomAccess class

CodePudding user response:

Replacing string in file is not so simple. You have to read whole file and rewrite part that you want to leave unchanged. Only when condition of comparing userID and data[0] is met, you would use replace() function to change user balance.

Your file is basically CSV file with space as line separator, as already mentioned store file contents in array or BufferedReader, change appropriate line and then export back to CSV.

  •  Tags:  
  • Related