java基础之 IO 流(RandomAccessFile类)

 

 

RandomAccessFile类的代码实战 

第一步:准备一个要进行读写的文本文件,如下图:

第二步:对该文本文件进行 操作

package IOTest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;

/**
 * ClassName: RandomAccessFileTets <br/>
 * Description: <br/>
 * date: 2021/8/2 19:47<br/>
 *
 * @author yiqi<br />
 * @since JDK 1.8
 */
public class RandomAccessFileTets {
    public static void main(String[] args) throws Exception {
        //创建一个文件流---要读取的文件
        File file1 = new File("src/IOTest/test.txt");
        //创建一个文件流---要输出的文件
        File file2 = new File("src/IOTest/clone.txt");
        //创建 raf1 、 raf2
        RandomAccessFile raf1 = new RandomAccessFile(file1,"r");
        RandomAccessFile raf2 = new RandomAccessFile(file2,"rw");
        //设置文件开始文字的指针
        raf1.seek(2);
        raf2.seek(3);
        while (true){
            //读取数据 当读取的数据为 -1 的时候 表示数据读取完成
            //read() 之后指针是自动往后移动
            int readData = raf1.read();
            if (readData == -1){
                System.out.println("数据读取完成");
                break;
            }
            raf2.write(readData);
        }
        raf1.close();
        raf2.close();
    }
}

 第三步:效果展示

注意知识点:

read(byte b[], int off, int len)

read(byte b[], int off, int len)

作用:规定一次读取多少数据

参数一:byte b[] 用来装数据的 字节数组
参数二:从 b 的第几个位置开始装
参数三:装 len 个长度的数据到 b中
off + len <= b的长度 ,否则会报数组越界的错误
package IOTest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;

/**
 * ClassName: RandomAccessFileTets <br/>
 * Description: <br/>
 * date: 2021/8/2 19:47<br/>
 *
 * @author yiqi<br />
 * @since JDK 1.8
 */
public class RandomAccessFileTets {
    public static void main(String[] args) throws Exception {
        //创建一个文件流---要读取的文件
        File file1 = new File("src/IOTest/test.txt");
        //创建一个文件流---要输出的文件
        File file2 = new File("src/IOTest/clone.txt");
        //创建 raf1 、 raf2
        RandomAccessFile raf1 = new RandomAccessFile(file1, "r");
        RandomAccessFile raf2 = new RandomAccessFile(file2, "rw");
        //设置一次性读取数据的长度
        byte[] buffer = new byte[4];
//        while (true){
        //读取数据 当读取的数据为 -1 的时候 表示数据读取完成
        //read() 之后指针是自动往后移动
        int readData = raf1.read(buffer,2,2);
        System.out.println("readData -> " + new String(buffer));
        raf1.close();
        raf2.close();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

super码王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值