Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java add text to a specific line in a file

Tags:

java

file

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

like image 426
user3718160 Avatar asked May 17 '16 13:05

user3718160


People also ask

How do I add text to an existing file in Java?

Likewise, the text to be added is stored in the variable text . Then, inside a try-catch block we use Files ' write() method to append text to the existing file. The write() method takes the path of the given file, the text to the written, and how the file should be open for writing.

How do you replace a specific line in a file using Java?

Invoke the replaceAll() method on the obtained string passing the line to be replaced (old line) and replacement line (new line) as parameters. Instantiate the FileWriter class. Add the results of the replaceAll() method the FileWriter object using the append() method.

How do I add something to a Java file?

You can append text into an existing file in Java by opening a file using FileWriter class in append mode. You can do this by using a special constructor provided by FileWriter class, which accepts a file and a boolean, which if passed as true then open the file in append mode.


2 Answers

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);
like image 100
M. Suurland Avatar answered Sep 29 '22 18:09

M. Suurland


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

like image 38
Daniel Gutierrez Avatar answered Sep 29 '22 18:09

Daniel Gutierrez