How can I write to a specific line number in a txt file in Java

[亡魂溺海] 提交于 2019-12-01 16:24:08
Cyäegha

A quick and dirty solution would be to use the Files.readAllLines and Files.write methods to read all lines, change the one you want to change, and overwrite the whole file:

List<String> lines = Files.readAllLines(file.toPath());
lines.set(line, dataType.toUpperCase() + ":" + newData);
Files.write(file.toPath(), lines); // You can add a charset and other options too

Of course, that's not a good idea if it's a very big file. See this answer for some ideas on how to copy the file line by line in that case.

Regardless of how you do it, though, if you are changing the byte length of the line, you will need to rewrite the whole file (AFAIK). RandomAcessFile allows you to move around the file and overwrite data, but not to insert new bytes or removes existing ones, so the length of the file (in bytes) will stay the same.

Alex K

Here is a link to a question just like this with a great answer: I want to open a text file and edit a specific line in java

Basically, you can't just edit that line, unless it'll be the exact same length.

Instead, you'll want to copy over every line, and then when you reach the line number of the line you want to change, instead of copying over the old line, just put in your new line.

The link I gave you has a great example on how to do this.

I hope this helps...if not, let me know, and I'll elaborate further on the post. Good luck :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!