Package File;import Java.io.file;import Java.io.fileinputstream;import java.io.fileoutputstream;import Java.io.ioexception;import java.io.randomaccessfile;/* uses the Randomaccessfile class to insert content at the specified file location. */public class Insertcontent {public static void insert (String fileName, Long pos, String insertcontent) throws IOException {File tmp = file.createtempfile ("tmp", null); Tmp.deleteonexit (); try (randomaccessfile RAF = new Randomaccessfile ( FileName, "RW"); FileOutputStream tmpout = new FileOutputStream (TMP); FileInputStream Tmpin = new FileInputStream (tmp)) {Raf.seek (POS); byte[] buf = new Byte[64];int Hasread = 0;while ((hasread = Raf.read (BUF)) >0) {tmpout.write (buf, 0, hasread);} Raf.seek (POS); Raf.write (Insertcontent.getbytes ()); while ((Hasread = Tmpin.read (buf)) >0) {raf.write (buf,0), Hasread);}}} public static void Main (string[] args) throws Ioexception{insert ("./src/file/insertcontent.java", 45, "Insert content!\n");}}
Use the Randomaccessfile class to insert content at the specified file location