2

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?

Community
  • 1
  • 1
Max Gabderakhmanov
  • 912
  • 1
  • 18
  • 36
  • You need to actually understand the code, and not just copy and paste it. If you understand what it does, adapting it becomes easy. Note that the code you posted is horribly inefficient, and has several bugs. Read http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html – JB Nizet Jun 18 '15 at 21:57

2 Answers2

2

Instead of performing the replacement on the whole string, do it while reading. This way you can count the lines and only apply it to the second one:

BufferedReader file = new BufferedReader(new FileReader(targetFile));
String line;
String input = "";
int count = 0;

while ((line = file.readLine()) != null) {
    if (count == 1) {
        line = line.replace(toUpdate, updated);
    }
    input += line + "\n";
    ++count;
}

Note, though, that using the + operator on strings, especially in a loop, is usually a bad idea, and you should probably use a StringBuilder instead:

BufferedReader file = new BufferedReader(new FileReader(targetFile));
String line;
StringBuilder input = new StringBuilder();
int count = 0;

while ((line = file.readLine()) != null) {
    if (count == 1) {
        line = line.replace(toUpdate, updated);
    }
    input.append(line).append('\n');
    ++count;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

You could introduce boolean variable and set it to true when you do first update. When you parse line, before doing update check the variable and only do update if it is false. This way, you will update first line with that contains target String, be it second line or some other.

You should do update while reading from file for this to work.

John
  • 5,189
  • 2
  • 38
  • 62