java實(shí)現(xiàn)倒序讀取文件功能示例分享
Long end,long num,File file,String charset
4個(gè)參數(shù)說(shuō)明
end 相當(dāng)于坐標(biāo) ,tail 向上的起點(diǎn),num是讀取的行數(shù),file 目標(biāo)文件 charset字符集 默認(rèn)UTF8
end 為 null 代表從 文件 最末端 向上 獲取。
Map m=FileUtil.tail(null,10,file,null)//讀取文件最后10行,結(jié)果在 m.get(FileUtil.ARR) 里
FileUtil.tail(m.get(FileUtil.POINT),3,file,null)//讀取文件倒數(shù) 11行到13行,其實(shí)就是接著上邊的第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){//獲取的行數(shù)不夠,并且沒(méi)有到達(dá)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;
}
}
相關(guān)文章
Mybatis的mapper標(biāo)簽 namespace屬性用法說(shuō)明
Java?CyclicBarrier錯(cuò)誤使用的實(shí)例
SpringBoot訪問(wèn)接口自動(dòng)跳轉(zhuǎn)login頁(yè)面的問(wèn)題及解決
springboot簡(jiǎn)單接入websocket的操作方法
關(guān)于Java垃圾回收開(kāi)銷降低的幾條建議
SpringBoot整合canal實(shí)現(xiàn)數(shù)據(jù)緩存一致性解決方案

