RandomAccessFile文件读取工具类

RandomAccessFile

java.io包下文件读写工具类,能够设置偏移量读取文件

需求

将系统输出的日志文件读取出来,给前端展示在页面上

思路

日志文件的配置最大为20M,一次性读取整个文件是不可取的。所以就考虑“分页读取”,一次性读取多少行返回前端,然后前端请求翻页。java中有没有象C那样有偏移指针的工具类来读取文件?

实现

	/**
     * 获取日志内容
     * @param fileName 文件名
     * @param offset 文件读取的偏移量
     * @return
     */
    public DetailLogResponse readFile(String fileName, long offset) {
        List<String> content = new ArrayList<>();
        String filePath = UrlUtils.contact(logHome, fileName);
        DetailLogResponse response = new DetailLogResponse(fileName, offset, content);
        File file = new File(filePath);
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) {
            randomAccessFile.seek(offset);
            for (int i = 0; i < lineNumber; i++) {
            	// 防止阻塞
                if (randomAccessFile.getFilePointer() >= randomAccessFile.length() - 500) {
                    break;
                } else {
                    content.add(randomAccessFile.readLine());
                }
            }
            response.setOffset(randomAccessFile.getFilePointer());
        } catch (IOException e) {
            log.error("获取目标日志出错{}", filePath);
        }
        return response;
    }

API

public RandomAccessFile(File file, String mode) 第二个参数看源码得知有r、rw、rws、rwd四种模式

	if (mode.equals("r"))
        imode = O_RDONLY;
    else if (mode.startsWith("rw")) {
        imode = O_RDWR;
        rw = true;
        if (mode.length() > 2) {
            if (mode.equals("rws"))
                imode |= O_SYNC;
            else if (mode.equals("rwd"))
                imode |= O_DSYNC;
            else
                imode = -1;
        }
    }

seek(long) 设置偏移量
getFilePointer() 获取当前的偏移量
length() 获取文件长度

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值