java RandomAccessFile的使用


RandomAccessFile:提供的对文件内容的访问,既可以读文件,也可以写文件;支持随机访问文件,可以访问文件的任何位置

  • 打开文件有两种模式 “rw”(读写) 和“r”(只读),RandomAccessFile raf = new RandomAccessFile(file, “rw”);
  • raf.seek(0);//定位指针位置,读取文件初始值是0,从开头读取
  • 写方法raf.write(char) –>只写一个字节(后8位),同时指针指向下一个位置,准备再次写入
  • 读方法int b = raf.read() –> 只读一个字节
  • 文件读写完成之后一定要关闭,避免出现一些异常情况

RandomAccessFile示例

    File file = new File(path, fileName); 
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
    //打印指针 
    System.out.println("文件指针初始:" + randomAccessFile.getFilePointer()); 
    //写入 
    randomAccessFile.write('b');//每次写入一个字节 
    //randomAccessFile.writeBytes("郑海龙");//用writeBytes写入中文,默认用ansi编码        
    //randomAccessFile.write("萨达".getBytes());默认用项目的编码
    randomAccessFile.seek(0);
    byte[] buff = new byte[1];
    String s1 = new String(buff); System.out.print(s1);
    randomAccessFile.seek(1); 
    byte[] buff2 = new byte[9];
    randomAccessFile.read(buff2);
    System.out.println(s2);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值