标签:
package File;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
/*利用RandomAccessFile类在指定文件指定位置插入内容。*/
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,"插入内容!\n");
}
}
利用RandomAccessFile类在指定文件指定位置插入内容
标签:
原文地址:http://www.cnblogs.com/masterlibin/p/4786806.html