简体   繁体   English

在while循环中替换字符串的最佳方法是什么

[英]What is the best way to replace string in while loop

What is the best way to replace a string in a while loop that reads lines from a file? 在从文件中读取行的while循环中替换字符串的最佳方法是什么?

while ((line = reader.readLine()) != null) {
 if (line.contains("blabla")) {
  line = line.replaceAll("blabla", "eee");
 }
 writer.write(line);
}

is this correct way, I want to read all file lines, and check each line if contains this word, there is only one line that contains this word, if it contains it then replace this word and do not check another lines. 这是正确的方法,我想读取所有文件行,并检查每一行是否包含此单词,只有一行包含此单词,如果包含该单词,则替换此单词,而不检查另一行。

You can use a boolean flag as a condition in your while and update it in your if: 您可以在一段时间内使用布尔值标志作为条件,并在if中更新它:

boolean found = false;
while ((!found) && ((line = reader.readLine()) != null)) {
 if (found = line.contains("blabla")) {
  line = line.replaceAll("blabla", "eee");
 }
 writer.write(line);
}

You can use replace this, 您可以使用替换此,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM