如何在Java中的txt文件中间添加新行 [英] How to add new line in the middle of txt file in java

查看:73
本文介绍了如何在Java中的txt文件中间添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在Java中修改文本文件.例如,这是修改之前的文件

I have to modify a text file in java. eg this is the file before modify

line
line
line 
line
line 
line

,它看起来应该像:

line
line
this is another 
line
line
line
line

因此,请勿覆盖任何内容,只需在2.和3.行之间添加一行,原始的3.行将是新的4.行.

So don't write over anything, only add a line between the 2. and 3. line, and the original 3. line will be the new 4. line.

一种方法是制作一个临时文件,在其中写入每一行,然后在要修改的地方进行修改.比删除原始文件,然后重命名临时文件.或读取临时文件并将其写入原始文件.但是,有什么方法可以像我想在Java中使用相同的类那样读取和修改文件吗?谢谢!

A way is to make a temp file, write every line in it, and where I want to modify I do the modification. Than delet the original, and rename the temp file. Or read the temp file and write it to te original file. But is there any way to read and modify a file like I want using the same class in java? thx!

推荐答案

您可以同时在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.

这篇关于如何在Java中的txt文件中间添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆