1 Packagefile;2 3 ImportJava.io.File;4 ImportJava.io.FileInputStream;5 ImportJava.io.FileOutputStream;6 Importjava.io.IOException;7 ImportJava.io.RandomAccessFile;8 9 Ten Public classinsertcontent { One A Public Static voidInsert (String fileName,LongPos,string insertcontent)throwsioexception{ -File tmp = file.createtempfile ("tmp",NULL); - tmp.deleteonexit (); the Try( -Randomaccessfile RAF =NewRandomaccessfile (FileName, "RW"); -FileOutputStream tmpout =NewFileOutputStream (TMP); -FileInputStream Tmpinputstream =NewFileInputStream (TMP) + ){ - //move the record pointer to the end of the file append content + //Raf.seek (Raf.length ()); A at //move the record pointer to the specified position - Raf.seek (POS); - - byte[] Bbuf =New byte[64]; - - intHasread = 0; in -StringBuffer SBF =NewStringBuffer (); to + while((Hasread = Raf.read (bbuf)) > 0 ){ -Tmpout.write (bbuf, 0, hasread); theSbf.append (NewString (BBUF)); * } $ System.out.println (sbf.tostring ());Panax Notoginseng - Raf.seek (POS); the + Raf.write (Insertcontent.getbytes ()); A the while((Hasread = Tmpinputstream.read (bbuf)) > 0) { +Raf.write (bbuf, 0, hasread); - } $ } $ } - - Public Static voidMain (string[] args) { the Try { -Insert ("F:/new 1.txt", "AJSDKJFKSLDJFKL");Wuyi}Catch(IOException e) { the e.printstacktrace (); - } Wu } -}
Randomaccessfile Operating files