IO——RandomAccessFile(随机访问文件)

一、构造函数

mode参数:

含意

"r" 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException
"rw" 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。
"rws" 打开以便读取和写入,对于 "rw",还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。
"rwd"   打开以便读取和写入,对于 "rw",还要求对文件内容的每个更新都同步写入到底层存储设备。

二、特殊方法

(1)long getFilePointer()——获取当前偏移量
返回:到此文件开头的偏移量(以字节为单位),在该位置发生下一个读取或写入操作。
(2)void seek(long pos)——设置偏移量

注:偏移量的设置可能会超出文件末尾。偏移量的设置超出文件末尾不会改变文件的长度。只有在偏移量的设置超出文件末尾的情况下对文件进行写入才会更改其长度。
参数:
pos - 从文件开头以字节为单位测量的偏移量位置,在该位置设置文件指针。

三、使用

    //数据追加
    public static void append(String str) throws IOException {
        String path = "C:\\Users\\WANNCY\\Desktop\\hello.txt";
        RandomAccessFile raf = new RandomAccessFile(path, "rw");
        //写入
        raf.write("hello".getBytes());
        //返回文件当前的偏移量
        long pointer = raf.getFilePointer();
        raf.seek(pointer);
        //写入追加的字符串
        raf.write(str.getBytes());

        raf.seek(0);
        //读操作
        byte[] bs = new byte[10];
        int read = 0;
        while((read = raf.read(bs)) != -1){
            System.out.print(new String(bs,0,read));
        }
        System.out.println();
    }
    //指定位置插入

    /**
     *
     * @param path  路径
     * @param pos   指定位置
     * @param str   插入字符串
     * @throws IOException
     * 1、将内容插入到指定位置(pos > 0)
     * 2、使用RandomAccessFile(随机访问文件),设置偏移量
     * 3、将指定位置后的数据存储
     * 4、写入插入数据
     * 5、读取之前存储的数据,再次追加到文件中
     * 6、关闭流
     */
    public static void skip(String path,int pos,String str) throws IOException {
        if(pos < 0){
            return;
        }
        //打开随机访问文件流
        RandomAccessFile raf = new RandomAccessFile(path,"rw");
        //创建临时文件****************
        File tmp_file = File.createTempFile("tmp",null);//创建临时文件方法,不需要指定路径
        //将偏移量设为指定位置
        raf.seek(pos);
        //将指定位置后数据读到临时文件中进行存储
        byte[] bytes = new byte[10];
        int read = 0;
        //打开临时文件相应的输入输出流
        FileInputStream inputStream = new FileInputStream(tmp_file);
        FileOutputStream outputStream = new FileOutputStream(tmp_file);
        while((read = raf.read(bytes)) != -1){
            outputStream.write(new String(bytes,0,read).getBytes());
        }
        outputStream.close();
        //写入插入数据
        raf.seek(pos);
        raf.write(str.getBytes());
        //将临时文件中的数据读到文件中
        byte[] bytes2 = new byte[10];
        int read2 = 0;
        while((read2 = inputStream.read(bytes2)) != -1){
            raf.write(new String(bytes2,0,read2).getBytes());
        }
        inputStream.close();
        raf.close();
    }


 

猜你喜欢

转载自blog.csdn.net/weixin_42479293/article/details/88776935