java 向文件指定行添加,Java将文本添加到文件中的特定行

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

For example myFile :

1: line 1

2: line 2

3: line 3

4: line 4

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 ?

Thank you

解决方案

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

List lines = Files.readAllLines(path, StandardCharsets.UTF_8);

lines.add(position, extraLine);

Files.write(path, lines, StandardCharsets.UTF_8);

To give an example:

Path path = Paths.get("C:\\Users\\foo\\Downloads\\test.txt");

List 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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值