栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现倒序读取文件功能示例分享

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现倒序读取文件功能示例分享

Long end,long num,File file,String charset
4个参数说明
end 相当于坐标 ,tail 向上的起点,num是读取的行数,file 目标文件 charset字符集 默认UTF8
end 为 null 代表从 文件 最末端 向上 获取。

Map m=FileUtil.tail(null,10,file,null)//读取文件最后10行,结果在 m.get(FileUtil.ARR) 里
FileUtil.tail(m.get(FileUtil.POINT),3,file,null)//读取文件倒数 11行到13行,其实就是接着上边的第10行再向上读3行

复制代码 代码如下:
public class FileUtil {

    private static final long step=5000;

    public static final String ARR="arr";
    public static final String POINT="point";

    public static Map tail(Long end,long num,File file,String charset)throws Exception{
        if(num<=0||(end!=null&&end<0)){
            throw new IllegalArgumentException();
        }
        Map map=new HashMap();
        RandomAccessFile acc=null;
        try {
            acc = new RandomAccessFile(file, "r");
            long temp_end = (end == null ? acc.length() : end);
            long my_point = temp_end > step ? (temp_end-step) : 0;
            acc.seek(my_point);
            linkedList queue = new linkedList();
            String temp;
            int n=0;
            while((temp=acc.readLine())!=null){
                if(++n==1&&my_point!=0){
                    continue;
                }
                Object[]  objects=new Object[2];
                long point = acc.getFilePointer();
                if(point>=temp_end&&end!=null){break;}
                objects[0]=point;
                objects[1]=new String(temp.getBytes("8859_1"),charset);
                if(queue.size()==num){
                    queue.poll();
                }
                queue.offer(objects);
            }

            if(queue.size()0){
                long last_num=num-queue.size();
                Object[] header = queue.peek();
                if(header==null){throw new RuntimeException("FileUtil step:"+step+" not enough long");}
                Map m = tail((Long)header[0], last_num, file,charset);
                map.put(POINT,m.get(POINT));
                map.put(ARR,ArrayUtils.addAll((Object[])m.get(ARR),queue.toArray()));
            }else if(queue.size()>0){//获取的行数不够,并且没有到达TOP
                map.put(POINT,queue.peek()[0]);
                map.put(ARR,queue.toArray());
            }
        }finally {
            if(acc!=null){
                try {
                    acc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }


}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152257.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号