前面的程序只能够实现在文件后面追加内容,而不能在文件中间插入内容,否则会覆盖插入位置的文件内容,要实现在文件中插入内容,只需要设置一个缓存的临时文件存储插入位置后面的文件内容即可。
public class InsertContext { 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("newFile.txt", 45, "插入的内容\r\n"); } }