利用RandomAccessFile类在指定文件指定位置插入内容
2015-09-06 17:53
405 查看
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"); } }
相关文章推荐
- 磁盘管理及文件系统管理
- Apache windows安装
- jenkins , ant ctomcat+shell报ant: command not foun.
- Visual Studio 项目模板制作(二)
- python3入门之函数
- 6-8月份工作总结(一)——Kongsberg公司演示EM2040C和TOPAS
- JVM学习笔记(一)------基本结构
- DuiLib : 执行按钮事件, 模拟按钮的点击
- Android改变TextView中部分字体颜色
- Web端 Cookie Session ViewData ViewBag
- Android实例-操作摄像头(XE8+小米2)
- java中通过类名实例化类
- jquery插件集合
- 数据结构中的查找算法-哈希表(3)
- Lua图文混排
- Android IntentService完全解析 当Service遇到Handler
- 各种DIV布局单元
- 在使用python requests 库时,通过post上传名称为中文文件时我遇到的问题
- python3入门之函数
- 2015.09.06 C++的sizeof和strlen()