简体   繁体   English

替换文本文件的一行

[英]Replace one line of a text file

I'm trying to read the first line of a text file and then replacing that line with something different.我正在尝试读取文本文件的第一行,然后用不同的内容替换该行。 The first line is an int value, so first I changed it to +1 of what is currently.第一行是一个 int 值,所以首先我将其更改为当前值的 +1。

BufferedWriter writer = new BufferedWriter( new FileWriter("file.txt", true)); 

BufferedReader reader = new BufferedReader( new FileReader("file.txt"));

String amount;

amount = reader.readLine();

int amount1 = Integer.parseInt(amount);
amount1 = amount1 + 1;
String amount2 = String.valueOf(amount1);
amount = amount.replace(amount, amount2);

writer.write(amount);

Instead of replacing the original value with the new value, it just writes the new value next to the old one.它不是用新值替换原始值,而是将新值写在旧值旁边。

Well, you told the writer to append instead of replace via the second constructor argument of the FileWriter :好吧,您通过FileWriter的第二个构造函数参数告诉作者追加而不是替换:

BufferedWriter writer = new BufferedWriter( new FileWriter("file.txt", true)); 

If you want to replace the file, you have to set append to false:如果要替换文件,则必须将append设置为 false:

BufferedWriter writer = new BufferedWriter( new FileWriter("file.txt", false)); 

However, this replaces the entire file not just the first line.但是,这会替换整个文件,而不仅仅是第一行。

If you are using a recent version of Java, you can do this:如果您使用的是最新版本的 Java,您可以这样做:

try (BufferedReader reader = new BufferedReader( new FileReader("file.txt"));
        Writer writer = new FileWriter("newfile.txt")) {
    String firstLine = reader.readLine();
    firstLine = Integer.toString(Integer.parseInt(firstLine) + 1);
    writer.writeLine(firstLine);
    reader.transferTo(writer);
}

And then replace file.txt with newfile.txt然后将 file.txt 替换为 newfile.txt

You must replace the entire file when changing a text file.更改文本文件时必须替换整个文件。

Path path = Paths.get("file.txt");
Charset charset = Charset.defaultCharset();
List<String> lines = Files.readAllLines(path, charset);
String firstLine = lines.get(0);
...
lines.set(0, firstLines);
Files.write(path, lines, charset);

However if you take care that the first line never changes in length, and has enough room, you could use a RandomAccessFile , and only change that piece of text.但是,如果你注意第一行的长度永远不会改变,并且有足够的空间,你可以使用RandomAccessFile ,并且只更改那段文本。

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

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