Karthik Karthik - 1 year ago 132
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_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";

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);
} catch (IOException ioe) {

I appreciate any help with this.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download