RandomAccessFile实践

RandomAccessFileDemo随机读取文件,实现了DataInput和DataOutput接口,能够读入和写出文件。
该类实例需要两个参数:一个文件或文件路径,二个是mode访问模式,r表示读,rw表示读+写。
getFilePointer()  获取文件指针,返回一个long类型文件指针所在位置。
seek(fp)          设置文件指针位置。  

 

 

package io.test6;

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

/**
 * @author yf
 **/
public class RandomAccessFileDemo {
    public static void main(String[] args) throws Exception {


        File file = new File("test6/out.txt");
        // System.out.println(RandomMode.R);
        //   write(file);
        read(file);
    }

    private static void read(File file) throws Exception {
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        //randomAccessFile.seek(1);//直接移动文件指针,指针从1开始,每个字节数量为1
        long filePointer = randomAccessFile.getFilePointer();
        System.out.println("文件指针位置:" + filePointer);
        byte b = randomAccessFile.readByte();
        System.out.println(b);


        long filePointer2 = randomAccessFile.getFilePointer();
        System.out.println("文件指针位置:" + filePointer2);
        byte c = randomAccessFile.readByte();
        System.out.println(c);

        randomAccessFile.close();
    }

    private static void write(File file) throws Exception {
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        randomAccessFile.writeByte(65);
        randomAccessFile.writeByte(66);
        randomAccessFile.close();
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值