在从文件中读取行的while循环中替换字符串的最佳方法是什么?
while ((line = reader.readLine()) != null) {
if (line.contains("blabla")) {
line = line.replaceAll("blabla", "eee");
}
writer.write(line);
}
是正确的方法,我想读取所有文件行,并检查每一行是否包含该单词,只有一行包含该单词,如果包含该单词则替换此单词,而不检查另一行。
答案 0 :(得分:1)
您可以在一段时间内使用布尔标志作为条件,并在以下条件下对其进行更新:
boolean found = false;
while ((!found) && ((line = reader.readLine()) != null)) {
if (found = line.contains("blabla")) {
line = line.replaceAll("blabla", "eee");
}
writer.write(line);
}
答案 1 :(得分:0)
您可以使用替换此内容
File your_file = new File(filePath)
String oldContent = “”;
BufferedReader reader = new BufferedReader(new FileReader(your_file));
String line = reader.readLine();
while (line != null)
{
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
String newContent = oldContent.replaceAll("wantToBeReplace", newString);
FileWriter writer = new FileWriter(your_file);
writer.write(newContent);
reader.close();
writer.close();