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

Christoph
  • 93
  • 4
user3718160
  • 481
  • 2
  • 11
  • 23
  • 2
    You may use http://stackoverflow.com/questions/289965/inserting-text-into-an-existing-file-via-java – nikli May 17 '16 at 13:04

2 Answers2

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);
M. Suurland
  • 725
  • 12
  • 31
  • 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 – user3718160 May 17 '16 at 13:24
  • Please check the following: http://stackoverflow.com/questions/17714584/what-is-project-language-level-in-intellij-idea – M. Suurland May 17 '16 at 13:32
  • Even with that I keep seeing an error in my IDE but the code run so I will just ignore it thanks a lot ! – user3718160 May 17 '16 at 13:47
  • Welcome :) I am not running InteliJ (running Eclipse myself), but i guess it is related to your IDE. – M. Suurland May 17 '16 at 13:50
  • 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? – Chris F Jan 15 '20 at 21:22
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