Reputation: 60
I'm trying to replace several strings in one method using a HashMap but currently I can just get it to work with the first string in Map.
Previously I was using a "replaceAll" method for each String, which is hard to maintain because I'm trying to replace a changing list of Strings.
Can you give me any ideas?
Here's my code:
private static void string_change(String args[])
{
try
{
File file = new File("input_file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
Map<String, String> ReplacementMap = new HashMap<String, String>();
ReplacementMap.put("STRING1", "TEXT1");
ReplacementMap.put("STRING2", "TEXT2");
ReplacementMap.put("STRING3", "TEXT3");
String originalString = oldtext;
for (Map.Entry<String, String> entry : ReplacementMap.entrySet()) {
StringBuilder builder = new StringBuilder(originalString.replaceAll(entry.getKey(), entry.getValue()));
String newtext = builder.toString();
FileWriter writer = new FileWriter("output_file.txt");
writer.write(newtext);
writer.close();
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
Upvotes: 2
Views: 3569
Reputation: 393
The problem is, that you try to write the file for every entry in the map. So only the last entry is beeing applied to the target file. The better solution would be to apply all replacements before you write the file.
File file = new File("input_file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuffer buffer = new StringBuffer();
String line;
while((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\r\n");
}
reader.close();
Map<String, String> replacementMap = new HashMap<String, String>();
replacementMap.put("STRING1", "TEXT1");
replacementMap.put("STRING2", "TEXT2");
replacementMap.put("STRING3", "TEXT3");
String toWrite = buffer.toString();
for (Map.Entry<String, String> entry : replacementMap.entrySet()) {
toWrite = toWrite.replaceAll(entry.getKey(), entry.getValue()));
}
FileWriter writer = new FileWriter("output_file.txt");
writer.write(toWrite);
writer.close();
Upvotes: 4
Reputation: 77044
You're overwriting your output file each time through the loop. How about this?
String temp = originalString;
for (Map.Entry<String, String> entry : ReplacementMap.entrySet()) {
temp = temp.replaceAll(entry.getKey(), entry.getValue()));
}
FileWriter writer = new FileWriter("output_file.txt");
writer.append(temp);
writer.close();
Upvotes: 0