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?

1
  • 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 docs.oracle.com/javase/tutorial/essential/io/charstreams.html Commented Jun 18, 2015 at 21:57

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.