简体   繁体   中英

Java: replace only one line/string in the file

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?

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;
}

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.

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