如何在文件的特定位置写入内容
假设我有一个名为 abhishek.txt 的文件,其中包含以下行
我是,你叫什么名字。
现在我想写
阿布舍克
在“我是”之后就像我是阿布舍克一样,.. 如何直接把这个具体位置的内容写出来。
Suppose I have a file named abhishek.txt and that contains the following line
I am , and what is your name.
Now I want to write
Abhishek
after "I am" like I am Abhishek, ..
How to write the content in this specific position directly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您无法将数据插入文件...文件系统(通常)根本不支持此类操作。通常,您会打开一个文件进行读取,另一个进行写入,将文件的第一部分从一个流复制到另一个流,写入额外的部分,然后复制文件的第二部分。
如果您尝试替换原始文件,则需要将其删除并将新文件移动到位。
有时,一次性将整个文件读入内存可能会更简单 - 这取决于您想要执行的操作以及文件有多大。
You can't insert data into a file... file systems (in general) simply don't support such an operation. Typically you'd open one file for reading and another for writing, copy the first part of the file from one stream to the other, write the extra part, then copy the second part of the file.
If you're trying to replace the original file, you'd then need to delete it and move the new file into place.
Sometimes it may be simpler to read the whole file into memory in one go - it depends on exactly what you're trying to do, and how big the file is.
您无法将数据插入文件中。您可以使用
RandomAccessFile
覆盖特定位置的数据。然而,插入需要更改其后的所有数据。对于你的情况,尝试这样的事情:You can't insert data into a file. You can overwrite data at a specific location with
RandomAccessFile
. However an insert requires changing all of the data after it. For your case try something like this instead:一般来说,你需要读取旧文件,修改内存中的内容,然后再次写回。
这里有很多选项,例如是否一次读取全部文件,还是一次读取一小部分,是否替换现有文件等,但这通常是使用的模式。
Generally speaking you need to read the old file, modify the contents in memory and write it back out again.
There are many options here, as to whether you read the file all at once, or a small piece at a time, whether you replace the existing file, etc, but this is generally the pattern to use.
我设法使用 RandomAccessFile 来做到这一点:
通过此操作,您将获得一个完全包含预期“我是 Abhishek”内容的文件。
即使您想将其保留在文件中的第一行之后的内容(这是我最初的问题:我有一个大文件,我必须在某个字符串之后插入一些内容)而不是在文件末尾,这更容易。
I managed to do it using RandomAccessFile:
With this, you get a file containing exactly the expected 'I am Abhishek' content.
This works even if you would had content after the first line, which you want to keep in the file(this was my initial problem: I had a large file and I had to insert some content after a certain String) rather than write at the end of the file, which is easier.
您有三种选择:
You have three choices: