如何在文件的特定行之后插入文本 [英] How to insert text after a particular line of a file

查看:121
本文介绍了如何在文件的特定行之后插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个250行的文件。我想在第128行之后插入一些文字。

I have a file of 250 line. I wanted to insert some text after line 128.

我只发现我可以在文件末尾添加一个文本
,如

I only found that I can append a text at the end of file like

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //oh noes!
}

在这篇文章中找到如何将文本附加到Java中的现有文件

但没有提及行号或者......

But with no mention to the line number or sth.

推荐答案

没有办法插入文本由于文件系统的工作方式,文件的中间位置。它们实现了修改文件数据块以及从文件末尾添加和删除块的操作。他们没有实现的是在其他任何地方添加或删除数据块,因为这些操作的固有复杂性

There's no way to insert text in the middle of a file because of how file systems work. They implement operations to modify the data blocks of a file and to add and remove blocks from the end of a file. What they don't implement is adding or removing data blocks anywhere else because of inherent complexities of these operations.

您要做的是将前125行复制到新文件,添加您要添加​​的内容,然后复制文件的其余部分。如果您愿意,可以将新文件重命名为旧文件,这样就不会累积临时文件。

What you have to do is copy the first 125 lines to a new file, add what you want to add, and then copy the rest of the file. If you want to you can then rename the new file as the old file so you don't accumulate temporary files.

这篇关于如何在文件的特定行之后插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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