Java 文件随机读写流 RandomAccessFile

一.简述

1、是JAVA I/O流体系中功能最丰富的文件内容访问类,它提供了众多方法来访问文件内容。

2、由于可以自由访问文件的任意位置,所以如果需要访问文件的部分内容,RandomAccessFile将是更好的选择。

3、可以用来访问保存数据记录的文件,文件的记录的大小不必相同,但是其大小和位置必须是可知的。

RandomAccessFile类中比较重要的2个方法
方法名作用
getFilePointer()返回文件记录指针的当前位置
seek(long pos)将文件记录指针定位到pos的位置

 

二.使用方法

(1)java文件模型 
   在硬盘上的文件是byte byte存储的是数据的集合 
(2)打开文件 
   两种模式 “rw”(读写) “r“(只读) 
   RandomAccessFile raf = new RandomAccessFile(file,"rw") 
   文件指针,打开文件时指针在开头pointer = 0 
(3)写方法 
   raf.write(int) ---> 只写一个字节(后八位),同时指针指向下一个位置,准备再次写入 
(4)读方法 
   int b = raf.read() ---->读一个字节 
(5)关闭 
   文件读写完成以后一定要关闭(Oracle 官方说明)
public static void main(String[] args) throws IOException {
        File demo = new File("demo");
        if(!demo.exists()){
            demo.mkdir();
        }

        File file = new File(demo,"raf.dat");
        if(!file.exists()){
            file.createNewFile();
        }

        RandomAccessFile raf = new RandomAccessFile(file,"rw");
        //指针位置
        System.out.println(raf.getFilePointer());

        //只写了一个字节
        raf.write('A');
        System.out.println(raf.getFilePointer());
        raf.write('B');

        int i = 0x7fffffff;
        /**
         * 用write方法每次只能写一个字节,如果要把i写进去就得写4次
         */
        raf.write(i >>> 24);
        raf.write(i >>> 16);
        raf.write(i >>> 8);
        raf.write(i );
        System.out.println(raf.getFilePointer());

        /**
         * writeInt  直接写入
         */
        raf.writeInt(i);

        String s = "中";
        byte[] gbk = s.getBytes("gbk");
        raf.write(gbk);
        System.out.println(raf.length());


        //读文件,必须把指针移到头部
        raf.seek(0);
        //一次性读取,把文件中的内容都读到字节数组中
        byte[] buf = new byte[(int)raf.length()];
        raf.read(buf);
        System.out.println(Arrays.toString(buf));

        raf.close();

    }

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值