问题
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