用Java在文件中写入第x行
在Java中,假设我有一个包含n行的文本文件,是否可以只写入和替换第x行?或者我是否重写所有行以编辑任何行?
看来我已经使用 RandomAccess File 读取 x-1 行,然后调用
f.writeChars(str+"\n");
这行得通吗?但它也不会删除现有的第 x 行..
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..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅RandomAccessFile。
但这并不漂亮,因为如果你开始在给定位置书写,你就会覆盖那里的任何内容,所以你可能必须保存并重写该点之后的所有内容(也就是说,你不能只是“插入”文本在那里)。
回复:您的编辑:
它将删除现有的行,并且可能会删除更多(或更少),具体取决于行的长度。
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.
如果您不更改行长度,则只需覆盖原始数据即可。
如果您需要更改行长度,或者在文件中间添加(或删除)一行,那么您需要重写从该点开始直到结尾的所有数据。
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.