简体   繁体   中英

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 ((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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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