我正在尝试使用HashMap在一个方法中替换多个字符串,但是目前我可以使用它来处理Map中的第一个字符串。
以前我在为每个String使用“replaceAll”方法,这很难维护,因为我正在尝试替换更改的字符串列表。
你能给我任何想法吗?
这是我的代码:
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();
}
}
答案 0 :(得分:4)
问题是,您尝试为地图中的每个条目编写文件。因此,只有最后一个条目应用于目标文件。 更好的解决方案是在编写文件之前应用所有替换。
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();
答案 1 :(得分:0)
每次循环都会覆盖输出文件。怎么样?
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();