简体   繁体   中英

How to rewrite one specific line of a text file in java

The image below shows the format of my settings file for a web bot I'm developing. If you look at line 31 in the image you will see it says chromeVersion . This is so the program knows which version of the chromedriver to use. If the user enters an invalid response or leaves the field blank the program will detect that and determine the version itself and save the version it determines to a string called chromeVersion . After this is done I want to replace line 31 of that file with

"(31) chromeVersion(76/77/78), if you don't know this field will be filled automatically upon the first run of the bot): " + chromeVersion

To be clear I do not want to rewrite the whole file I just want to either change the value assigned to chromeVersion in the text file or rewrite that line with the version included.

Any suggestions or ways to do this would be much appreciated.

image

You will need to rewrite the whole file, except the byte length of the file remains the same after your modification. Since this is not guaranteed to be the case or to find out is too cumbersome here is a simple procedure:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Lab1 {

    public static void main(String[] args)  {
            String chromVersion = "myChromeVersion";
        try {
            Path path = Paths.get("C:\\whatever\\path\\toYourFile.txt");
            List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
            int lineToModify = 31;
            lines.set(lineToModify, lines.get(lineToModify)+ chromVersion);
            Files.write(path, lines, StandardCharsets.UTF_8);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Note that this is not the best way to go for very large files. But for the small file you have it is not an issue.

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