I have used the following code to replace text
to word
(taken from here):
String targetFile = "filename";
String toUpdate = "text";
String updated = "word";
public static void updateLine() {
BufferedReader file = new BufferedReader(new FileReader(targetFile));
String line;
String input = "";
while ((line = file.readLine()) != null)
input += line + "\n";
input = input.replace(toUpdate, updated);
FileOutputStream os = new FileOutputStream(targetFile);
os.write(input.getBytes());
file.close();
os.close();
}
and I have a file where I want replace only second line (text
):
My text
text
text from the book
The best text
It's work fine, but it replaced all toUpdate
strings in the file. How I can edit the code to replacing only one line/string (which completely like toUpdate
string) in the file?
The expected file should look like this:
My text
word
text from the book
The best text
Is this possible?