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

来源:互联网 发布:mac单机游戏推荐 编辑:程序博客网 时间:2024/06/05 12:26
<img src="http://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();}}}


0 0
原创粉丝点击