当前位置: 移动技术网 > IT编程>开发语言>Java > java实现倒序读取文件功能示例分享

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

2019年07月22日  | 移动技术网IT编程  | 我要评论
long end,long num,file file,string charset4个参数说明end 相当于坐标 ,tail 向上的起点,num是读取的行数,file 目

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<object[]> queue = new linkedlist<object[]>();
            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()<num&&my_point>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;
    }


}

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网