i got this code below to do replacing of a field that can be either String or Int but it is not working as expected. What i would like to do is inside the file player.dat the fields are "Username|Password|No. of Chips" i would like to replace the 3rd field based on username and i used string replace to change the old string to the new string but it is not working it is just adding the number next to the old value and all my data in file is messed up from the original line by line. Need some help on this
Current Output:
Username1|HashedPassword|200200Username2|HashedPassword2|300200Username3|HashedPassword3|300200
Expected Output
Username1|HashedPassword|200
Username2|HashedPassword|300
Username3|HashedPassword|200
Codes Shown Below.
public class testcode {
public static void main(String[] args) {
new testcode().replace();
}
public void replace() {
String oldFileName = "players.dat";
String tmpFileName = "tempmod.dat";
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = Integer.parseInt(UserCadd) + Integer.parseInt(Chips);
if (Username.equals(UserN))
line = Username + "|" + Password + "|" +totalChips;
bw.write("\r\n"+line);
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
}
}