JAVA读取文件指定的任意一行数据

本文介绍了一种使用RandomAccessFile类实现从文件中随机读取指定行的方法。通过预先记录每行的起始位置,可以快速定位并读取所需的行。这种方法适用于需要频繁访问特定行的大文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过RandomAccessFile读取文件指定的任意一行数据

直接看代码

/**
 * @Description 读取文件中指定的任意一行数据
 * @Date 2020/11/9 13:31
 * @Version 1.0
 */
public class RandomReadLine {
    public static final String FILE_NAME = "D:\\file\\test.dat";
    /** 记录每一行开头的指针位置 */
    public static final List<Integer> POINT_LIST = new ArrayList<>();
    static{
        try(BufferedReader br = new BufferedReader(new FileReader(FILE_NAME));){
            // 记录每一行字节大小
            int lineSize = 0;
            // 记录已读取到的字节总大小
            int totoalSize = 0;
            String readLine = null;
            while ((readLine = br.readLine())!=null){
                lineSize = readLine.getBytes().length;
                POINT_LIST.add(totoalSize);
                // 每行行末有换行符故需要+1
                totoalSize += lineSize+1;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        System.out.println(readLine(3));
    }

    public static String readLine(int lineNum){
        if(lineNum <= 0 || lineNum > POINT_LIST.size()){
            throw new IllegalArgumentException(String.format("lineNum must between %s and %s",0,POINT_LIST.size()));
        }

        try (RandomAccessFile raf = new RandomAccessFile(new File(FILE_NAME),"r");){
            raf.seek(POINT_LIST.get(lineNum-1));
            byte[] bytes = raf.readLine().getBytes("ISO-8859-1");
            return new String(bytes,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
    
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值