且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中的txt文件中间添加新行

更新时间:2023-12-03 16:04:46

您可以同时在Java文件中读取和修改文件.但是,问题在于,您需要在此处插入数据,以便重新整理新行之后的所有内容,然后扩展文件的长度.

You can read and modify to and from a file in Java at the same time. The problem you have though is that you need to insert data here, in order to do that everything after the new line needs to be shuffled down and then the length of the file extended.

具体取决于您要执行的操作以及执行操作的原因,有多种方法可以执行此操作,最简单的方法可能是扫描文件,然后将其复制到新位置,然后随心所欲地插入新值.但是,如果您需要就地编辑,那么它会更复杂,但实际上您会执行相同的操作:将X字符读取到缓冲区中,用新数据覆盖文件中的X字符,再读取下一个X字符.覆盖第一个缓冲区中的刚刚读取的字符.重复直到EOF.

Depending on exactly what and why you are trying to do there are a number of ways to do this, the easiest is probably to scan the file copying it to a new location and inserting the new values as you go. If you need to edit in place though then it's more complicated but essentially you do the same thing: Read X characters to a buffer, overwrite the X characters in the file with the new data, read next X characters. Overwrite the just-read characters from the first buffer. Repeat until EOF.