RandomAccessFile 实现向文件中插入一段内容
2015-12-10 11:28
609 查看
<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(); } } }
相关文章推荐
- java基础之java I/O框架(三)
- 黑马程序员------Properties和RandomAccessFile类
- Elyar的Java笔记--Java IO 操作
- JAVA学习——RandomAccessFile
- Java RandomAccessFile用法 (转的,写得非常很好!!)
- day day up--Java编程之RandomAccessFile操作系统属性文件
- RandomAccessFile和File的区别
- 黑马程序员---Java 编码解码的案例及特殊类RandomAccessFile
- java随机读取文件的内容
- java开发过程中对于乱码问题的解决方法
- javaIO中的类使用方法
- 网络编程--多线程断点下载文件
- Java_io体系之RandomAccessFile简介、走进源码及示例——20
- Java上路19-I/O-常用类
- Java RandomAccessFile用法(转载)
- Java / Android 基于Http的多线程下载的实现
- java Io 全解
- 黑马程序员_IO流(三)
- Java RandomAccessFile的使用
- RandomAccessFile