Karthik Karthik - 5 months ago 19
Java Question

Java: Replace multiple strings in a file and write it to a output file

I have a input file inputfile.txt with follwoing 3 lines:

REPLACE_STRING_1 is karthik
REPLACE_STRING_2 is 21
REPLACE_STRING_3 is chennai


I need to replace the replace_strings with different values and write the contents to a new file. But with the below code, I end up having 3 sets of same lines in the new file. How can I fix this? I want the final output to look like this:

name is karthik
age is 21
city is chennai


Here is my code:

try {
File file = new File("inputfile.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();

String ReplaceVar1 = oldtext.replaceAll("REPLACE_STRING_1", "name");
String ReplaceVar2 = oldtext.replaceAll("REPLACE_STRING_2", "age");
String ReplaceVar3 = oldtext.replaceAll("REPLACE_STRING_3", "city");

// Write updated record to a file
FileWriter writer = new FileWriter("outputfile.txt");
writer.write(ReplaceVar1 + ReplaceVar2 + ReplaceVar3);
writer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}


I appreciate any help with this.

Answer

You should change the new text and print only the last result.

String result = oldtext.replaceAll("REPLACE_STRING_1", "name")
                       .replaceAll("REPLACE_STRING_2", "age")
                       .replaceAll("REPLACE_STRING_3", "city");

Note that String is immutable and replaceAll returns the whole text, with the desired change.