write xth row in file in Java

我的梦境 提交于 2021-02-11 10:11:33

问题


in Java, suppose I have a text file with n rows, is it possible to only write and replace row x? or do I rewrite all the rows in order to edit any row?

It seems that I have use RandomAccess File to read x-1 lines, and then call

f.writeChars(str+"\n");

would this work? but also it won't delete the existing xth line..


回答1:


If you're not changing the line length, you can simply overwrite the original data.

If you need to change the line length, or add (or remove) a row in the middle of the file, then you need to rewrite all the data starting from that point till the end.




回答2:


See RandomAccessFile.

It wouldn't be pretty though because if you start writing in a given position you're overwriting whatever is there, so you will probably have to save and rewrite everything after that point (that is, you can't just "insert" text in there).

Re: your edit: It will delete the existing line and maybe more (or less) depending on the length of the line.



来源:https://stackoverflow.com/questions/6166386/write-xth-row-in-file-in-java

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