Insert a string in the middle of text file without replacing

Suppose i have a text file named Sample.text. i need advice on how to achieve this:

Sample.txt before running a program: ABCD

while running the program, user will input string to be added starting at the middle for example: user input is XXX

Sample.txt after running a program: ABXXXCD

Jon Skeet
people
quotationmark

Basically you've got to rewrite the file, at least from the middle. This isn't a matter of Java - it's a matter of what file systems support.

Typically the way to do this is to open both the input file and an output file, then:

  • Copy the first part from the input file to the output file
  • Write the middle section to the output file
  • Copy the remainder of the input file to the output file
  • Optionally perform file renaming if you want the new file to have the same eventual name as the original file

people

See more on this question at Stackoverflow