现在的位置: 首页 > 综合 > 正文

Java输入输出(7)—向指定文件,指定位置插入内容

2018年04月06日 ⁄ 综合 ⁄ 共 857字 ⁄ 字号 评论关闭

public class InsertContent

{

   public static void insert(String fileName,long pos,String insertContent) throws IOException

   {

     RandomAccessFile   raf = null;

     File tmp = File.createTempFile("tmp",null);

     FileOutputStream  tmpOut = null;

     FileInputStream  tmpIn = null;

     tmp.deleteOnExit();

     try

     {

       raf = new RandomAccessFile(fileName,"rw");

       tmpOut  = new FileOutputStream(tmp);

       tmpIn = new FileInputStream(tmp);

       raf.seek(pos);

       byte[] bbuf = new byte[64];

       int hasRead = 0;

       while((hasRead = raf.read(bbuf)) > 0)

      {

          tmpOut.write(bbuf,0,hasRead);

      }

      raf.seek(pos);

      raf.write(insertContent.getBytes());

      while((hasRead = tmpIn.read(bbuf))>0)

     {

       raf.write(bbuf,0,hasRead);
    }
 

     }

   finally

   {

     raf.close();

   }

   }

    public static void main(String[] args) throws IOException

   {

     insert("InsertContent.java", 45,"插入的内容\r\n");

   }

  

}

抱歉!评论已关闭.