Java将文本添加到文件中的特定行 [英] Java add text to a specific line in a file

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

问题描述

我想知道是否可以在带有Java的文件中添加一行。

I would like to know if it's possible to add a line in a File with Java.

例如myFile:

1: line 1
2: line 2
3: line 3
4: line 4

我想在第三行添加一个行fox示例,所以它看起来像这样

I would like to add a line fox example in the third line so it would look like this

1: line 1
2: line 2
3: new line
4: line 3
5: line 4

我发现如何在空文件或文件末尾添加文字但我不知道如何我不知道如何在文本中间执行它而不删除该行。

I found out how to add text in an empty file or at the end of the file but i don't know how to do it in the middle of the text without erasing the line.

另一种方法是将第一个文件分成两部分,然后创建一个文件添加第一部分新行然后第二部分因为感觉有点极端?

Is the another way than to cut the first file in 2 parts and then create a file add the first part the new line then the second part because that feels a bit extreme ?

谢谢

推荐答案

在Java 7+中,您可以使用 Files Path 类作为以下:

In Java 7+ you can use the Files and Path class as following:

List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);

举个例子:

Path path = Paths.get("C:\\Users\\foo\\Downloads\\test.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

int position = lines.size() / 2;
String extraLine = "This is an extraline";  

lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);

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

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