IO流——任意访问文件流

来源:互联网 发布:万网域名注册 .top 编辑:程序博客网 时间:2024/05/13 01:11
package com.qianfeng.demo02;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.RandomAccessFile;/** * 如果直接向中间插入内容,回导致后面的部分内容被覆盖掉。 * 怎么向中间插入内容,后面的部分依然保留呢? * 思路: * 把指定位置后面的内容放入到临时的文件当中,然后开始插入内容,然后插入完成之后在把文件当中的内容读取回来, * 删除临时的文件 * 1.要求操作的 * 2.临时文件 * 声明两个流 * 选择流: * 1.随机访问流 * 2.文件字节输出流 * */public class RandomDemo03 {public static void main(String[] args) {insertContent("raf.txt", 3, "哈哈哈哈哈哈");}public static void insertContent(String fileName,long pos,String content){RandomAccessFile raf = null;FileOutputStream fos = null;FileInputStream fis = null;try {//创建一个临时的文件,存储插入部分后面的内容File temp = File.createTempFile("temp", null);temp.deleteOnExit();   //程序结束后删除raf = new RandomAccessFile(fileName, "rw");fos = new FileOutputStream(temp);fis = new FileInputStream(temp);//移动指针到指定的位置raf.seek(pos);//读取插入点之后的内容,存储文件当中byte[]data = new byte[1024];int hasRead = 0;while ((hasRead = raf.read(data))!=-1) {//写入文件fos.write(data, 0, hasRead);}fos.flush();//指针回到插入位置raf.seek(pos);//插入内容raf.write(content.getBytes());//追加内容后面while ((hasRead = fis.read(data))!=-1) {raf.write(data, 0, hasRead);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {FileUtils.close(fis);FileUtils.close(fos);FileUtils.close(raf);}}}

0 0
原创粉丝点击