(原创)RandomAccessFile随机读取流

前言

RandomAccessFile是属于随机读取类,是可以对文件本身的内容直接随机进行操作的,可以在文件的指定位置
的读取和写入内容,这在很多时候都是很方便的。

1. 写入文件

public void write(View view) {
        String fileName = getFilesDir() + "/test.txt";
        String insertContent = "1234567890123456789012345678901234567890123456789012345678901234567890" +
                "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" +
                "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" +
                "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
        try {
            File file = new File(fileName);
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.write(insertContent.getBytes());
            raf.close();
            System.out.println("File length: " + new File(fileName).length());
        } catch (Exception e) {

        }

    }

3. 读取文件

public void read(View view) {
        String fileName = getFilesDir() + "/test.txt";
        try {
            RandomAccessFile raf = new RandomAccessFile(fileName, "r");
            // 需要读取的文件的大小
            System.out.println("raf.length(): " + raf.length());
            // 从第11字节开始读取
            int start = 10;
            raf.seek(start);
            // 跳过2个字节读取
            raf.skipBytes(2);
            // 每次读取的字节数
            byte[] bytes = new byte[1024];
            int byteRead ;
            while ((byteRead = raf.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, byteRead));
            }
            raf.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

效果图:









  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值