您的位置:首页 > 其它

RandomAccessFile 实现向文件中插入一段内容

2015-12-10 11:28 537 查看
<img src="https://img-blog.csdn.net/20151210113039877?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
import java.io.*;
public class RandomAccessFileTest1
{
public static void main(String []args)   throws IOException{
insertContent("test.txt",200L,"我是插入的内容、、、、");
}

public static void insertContent(String fileName,Long pos,String content) throws IOException{
File temp = File.createTempFile("tmp",null);
temp.deleteOnExit();
try(
//java7 的自动关闭try语句,可以自动执行 raf.close();
RandomAccessFile raf = new RandomAccessFile(fileName,"rw");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(temp));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(temp));
){

int hasReader = 0;
byte []buff = new byte[64];
<span style="white-space:pre">					</span>//指定插入点的位置
raf.seek(pos);
while((hasReader = raf.read(buff))>0){
bos.write(buff,0,hasReader);
}
raf.seek(pos);
raf.write(content.getBytes());

while((hasReader = bis.read(buff)) > 0){
raf.write(buff,0,hasReader);
}
}catch(IOException e){
e.printStackTrace();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息