我有一个输入文件inputfile.txt,后面有3行:
REPLACE_STRING_1 is karthik
REPLACE_STRING_2 is 21
REPLACE_STRING_3 is chennai
我需要用不同的值替换replace_strings并将内容写入新文件。但是使用下面的代码,我最终在新文件中有3组相同的行。我怎样才能解决这个问题?我希望最终输出看起来像这样:
name is karthik
age is 21
city is chennai
这是我的代码:
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";
}
reader.close();
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);
writer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
我很感激任何帮助。
答案 0 :(得分:2)
您应该更改新文本并仅打印最后一个结果。
String result = oldtext.replaceAll("REPLACE_STRING_1", "name")
.replaceAll("REPLACE_STRING_2", "age")
.replaceAll("REPLACE_STRING_3", "city");
请注意,String
是不可变的,replaceAll
会返回整个文本,并带有所需的更改。
答案 1 :(得分:0)
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";
}
reader.close();
System.out.println("Running ReplaceText");
// replace a word in a file
// REPLACE_STRING_1TENANT_ID REPLACE_STRING_1SOURCE_IP REPLACE_STRING_1USER_NAME REPLACE_STRING_1TARGET_HOSTNAME REPLACE_STRING_1MBODY_TIME
String newText = oldtext.replaceAll("REPLACE_STRING_1", "name");
newText = newText.replaceAll("REPLACE_STRING_2", "age");
newText = newText.replaceAll("REPLACE_STRING_3", "city");
// Write updated record to a file
FileWriter writer = new FileWriter("outputfile.txt");
writer.write(newText);
writer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
我测试了它,它给了我正确的输出
-MacBook-Pro-2:Desktop john$ cat outputfile.txt
name is karthik
age is 21
city is chennai