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

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;

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值