Java adds text to a specific line in a file
•
Java
I wonder if I can add a line to a file with Java
For example, myfile:
1: line 1 2: line 2 3: line 3 4: line 4
I want to add a line fox example on the third line, so it looks like this
1: line 1 2: line 2 3: new line 4: line 3 5: line 4
I've found how to add text to an empty file or at the end of a file, but I don't know how to execute it in the middle of the text without deleting lines
Another way is to divide the first file into two parts, then create a file, add the first part to the new part, and then add the second part, because it feels a little extreme?
thank you
Solution
In Java 7, you can use the files and path classes as follows:
List<String> lines = Files.readAllLines(path,StandardCharsets.UTF_8); lines.add(position,extraLine); Files.write(path,lines,StandardCharsets.UTF_8);
for instance:
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,StandardCharsets.UTF_8);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码