简体   繁体   English

如何在 java 中重写文本文件的特定行

[英]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.下图显示了我正在开发的 web 机器人的设置文件格式。 If you look at line 31 in the image you will see it says chromeVersion .如果您查看图像中的第 31 行,您会看到它chromeVersion This is so the program knows which version of the chromedriver to use.这样程序就知道要使用哪个版本的chromedriver 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 .如果用户输入无效响应或将该字段留空,程序将检测并确定版本本身并将其确定的版本保存到名为chromeVersion的字符串中。 After this is done I want to replace line 31 of that file with完成此操作后,我想将该文件的第 31 行替换为

"(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.需要明确的是,我不想重写整个文件,我只想更改文本文件中分配给chromeVersion的值,或者用包含的版本重写该行。

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.请注意,对于非常大的文件,这不是 go 的最佳方法。 But for the small file you have it is not an issue.但是对于您拥有的小文件,这不是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM