码迷,mamicode.com
首页 > 数据库 > 详细

IO(五)操作文件AccessFileDemo

时间:2016-04-18 11:23:56      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

public class AccessFileDemo {
    /*
        getFilePointer()    返回文件记录指针的当前位置,默认从0开始
        seek(long pos)    将文件记录指针定位到pos的位置
        r 代表以只读方式打开指定文件 
        rw 以读写方式打开指定文件 
        rws 读写方式打开,并对内容或元数据都同步写入底层存储设备 
        rwd 读写方式打开,对文件内容的更新同步更新至底层存储设备 
     */
    
    public static final File readFile = new File("D:" + File.separator + "intest.txt");
    static final long start = 2;

    public static void main(String[] args) throws Exception{
//        read();
//        readWithWrite();
        insert("对于 IO 流中RandomAccessFile 的测试", 2, "\nlucene是一个优秀的全文检索库");  
    }
    
    //读取
    public static void read() throws Exception {
        @SuppressWarnings("resource")
        RandomAccessFile file = new RandomAccessFile(readFile, "r");

        byte[] readByte = new byte[1024];

        int size = 0;

        while ((size = file.read(readByte)) != -1) {
            String res = new String(readByte, 0, size, "gbk");
            System.out.println(res);
        }
    }
    //追加
    public static void readWithWrite() throws Exception{
        RandomAccessFile access = new RandomAccessFile(readFile,"rw");
        access.seek(access.length());
        access.write("我是追加的".getBytes("gbk"));
        access.close();
        System.out.println("结束");
        
    }
    
    /** 
     * 实现向指定位置 
     * 插入数据 
     * @param fileName 文件名 
     * @param points 指针位置 
     * @param insertContent 插入内容 
     * **/  
    public static void insert(String fileName, long points, String insertContent) throws Exception {
        
            File tmp=File.createTempFile("tmp", null);  
            tmp.deleteOnExit();//当前线程死亡后删除。  
              
            RandomAccessFile raf = new RandomAccessFile(fileName, "rw");  
            //创建一个临时文件夹来保存插入点后的数据  
            FileOutputStream tmpOut=new FileOutputStream(tmp);  
            FileInputStream tmpIn=new FileInputStream(tmp);  
            raf.seek(points);  
            /**将插入点后的内容读入临时文件夹**/  
              
            byte [] buff=new byte[1024];  
            //用于保存临时读取的字节数  
            int hasRead=0;  
            //循环读取插入点后的内容  
            while((hasRead=raf.read(buff))>0){  
                // 将读取的数据写入临时文件中  
                tmpOut.write(buff, 0, hasRead);  
            }  
              
            //插入需要指定添加的数据  
            raf.seek(points);//返回原来的插入处  
            //追加需要追加的内容  
            raf.write(insertContent.getBytes());  
            //最后追加临时文件中的内容  
            while((hasRead=tmpIn.read(buff))>0){  
                raf.write(buff,0,hasRead);  
            }  
    }  
}

IO(五)操作文件AccessFileDemo

标签:

原文地址:http://www.cnblogs.com/DivineHost/p/5403583.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!