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(); } }