7

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

1

2 Answers 2

13

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

To give an example:

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);
Sign up to request clarification or add additional context in comments.

5 Comments

Hello I tried to use this but I get an IDE error "usage of api which is not available at the configured language level". Apparently Path & Files are documented as 1.6+ but I'm using Java version 1.7 so it should work wright ? I don't really get it
Please check the following: stackoverflow.com/questions/17714584/…
Even with that I keep seeing an error in my IDE but the code run so I will just ignore it thanks a lot !
Welcome :) I am not running InteliJ (running Eclipse myself), but i guess it is related to your IDE.
How can I extend this so I can add a line BEFORE a line with a certain string, e.g., add new line before that line that has line 4 in it?
1

You may read your file into an ArrayList, you can add elements in any position and manipulate all elements and its data, then you can write it again into file.

PD: you can not add a line directly to the file, you just can read and write/append data to it, you must manipulte de data in memory and then write it again.

let me know if this is useful for you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.