becks
becks

Reputation: 2718

How to insert text after a particular line of a file

I have a file of 250 line. I wanted to insert some text after line 128.

I only found that I can append a text at the end of file like

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //oh noes!
}

That is found on this post How to append text to an existing file in Java

But with no mention to the line number or sth.

Upvotes: 2

Views: 4338

Answers (3)

Saikat
Saikat

Reputation: 16720

The following code can help you to insert a given string at a given position in an existing file:

public static void writeStrToFileAtGivenLineNum(String str, File file, int lineNum) throws IOException { 
    List<String> lines = java.nio.file.Files.readAllLines(file.toPath());                                
    lines.add(lineNum, str);                                                                             
    java.nio.file.Files.write(file.toPath(), lines);                                                     
} 

Upvotes: 0

Joni
Joni

Reputation: 111219

There's no way to insert text in the middle of a file because of how file systems work. They implement operations to modify the data blocks of a file and to add and remove blocks from the end of a file. What they don't implement is adding or removing data blocks anywhere else because of inherent complexities of these operations.

What you have to do is copy the first 125 lines to a new file, add what you want to add, and then copy the rest of the file. If you want to you can then rename the new file as the old file so you don't accumulate temporary files.

Upvotes: 5

dijkstra
dijkstra

Reputation: 1078

You can read the original file and write the content in a temp file with new line inserted. Then, delete the original file and rename the temp file to the original file name.

Upvotes: 1

Related Questions