title: How to replace several Strings in a file at once using HashMap in Java
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>Can you give me any ideas?</p>
  
  <p>Here's my code:</p>
  
  <pre><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&lt;String, String&gt; ReplacementMap = new HashMap&lt;String, String&gt;();
   ReplacementMap.put("STRING1", "TEXT1");
   ReplacementMap.put("STRING2", "TEXT2");
   ReplacementMap.put("STRING3", "TEXT3");
  
   String originalString = oldtext;
  
   for (Map.Entry&lt;String, String&gt; 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();
   }
  } 
  </code></pre>