1 package file; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.io.RandomAccessFile; 8 9 10 public class InsertContent { 11 12 public static void insert(String fileName,long pos,String insertContent) throws IOException{ 13 File tmp = File.createTempFile("tmp", null); 14 tmp.deleteOnExit(); 15 try( 16 RandomAccessFile raf = new RandomAccessFile(fileName, "rw"); 17 FileOutputStream tmpOut = new FileOutputStream(tmp); 18 FileInputStream tmpInputStream = new FileInputStream(tmp) 19 ){ 20 // 将记录指针移动文件末尾 追加内容 21 // raf.seek(raf.length()); 22 23 // 将记录指针移动指定位置 24 raf.seek(pos); 25 26 byte[] bbuf = new byte[64]; 27 28 int hasRead = 0; 29 30 StringBuffer sbf = new StringBuffer(); 31 32 while((hasRead = raf.read(bbuf)) > 0 ){ 33 tmpOut.write(bbuf, 0 , hasRead); 34 sbf.append(new String(bbuf)); 35 } 36 System.out.println(sbf.toString()); 37 38 raf.seek(pos); 39 40 raf.write(insertContent.getBytes()); 41 42 while ((hasRead = tmpInputStream.read(bbuf)) > 0) { 43 raf.write(bbuf , 0 , hasRead); 44 } 45 } 46 } 47 48 public static void main(String[] args) { 49 try { 50 insert("f:/new 1.txt", 45, "ajsdkjfksldjfkl"); 51 } catch (IOException e) { 52 e.printStackTrace(); 53 } 54 } 55 }
时间: 2024-10-02 14:31:19