读文件最后200行

最近负责的任务中有一个读取文件最后200行的任务,这里总结下自己的收获,由于文件量较大,考虑到任务的性能,故使用了RandomAccessFile按照偏移量去读取

public static String readLastLinesFor(String osPath , int lines , String charset){
        //通过获取文件偏移量
        RandomAccessFile randomAccessFile = null;
        try{
            StringBuilder sb = new StringBuilder();
            File file = new File(osPath);
            if (!file.exists() || file.isDirectory() || !file.canRead()) {
                return null;
            }
            randomAccessFile = new RandomAccessFile(file, "r");
			//文件总的偏移量
            long len = randomAccessFile.length();
            if(len == 0l){
                return "";
            }else{
				//取其前一位,循环找到200行的具体偏移量
                long pos = len -1;
                while(pos > 0 && lines > 0){
                    pos--;
					//获取当前pos
                    randomAccessFile.seek(pos);
                    if(randomAccessFile.readByte() == '\n'){
                        lines--;
                    }

                }
				//根据偏移量创建byte数组
                byte[] bytes = new byte[(int) (len - pos)];
                randomAccessFile.read(bytes);
				//编码按照个人需要,源码默认是"GB-2312"
                if(charset == null){
                    return new String(bytes);
                }else{
                    return new String(bytes, charset);
                }
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(randomAccessFile != null){
                    randomAccessFile.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return  "";
    }

 

最终页面也能正常完成显示功能, 另外由于读取返回的string 中的“/r/n”显示的内容并不会自动换行,需要加上对应的样式修饰

.span1{
    white-space: pre-line;
}

整理了碰到的上述问题,希望能帮助到各位了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值