Long end,long num,File file,String charset
4 parameter descriptions
end is equivalent to the coordinate, tail is the starting point upward, num is the number of lines read, and the file target file charset character set defaults to UTF8
If end is null, it means getting from the end of the file upwards.
Map m=FileUtil.tail(null,10,file,null)//Read the last 10 lines of the file, the result is in m.get(FileUtil.ARR)
FileUtil.tail(m.get(FileUtil.POINT),3,file,null)//Read the 11th to 13th line from the last line of the file. In fact, it means reading the 10th line above and then reading 3 lines upward.
Copy the code code as follows:
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[]>();
Stringtemp;
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 long enough");}
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){//The number of rows obtained is not enough, and it has not reached 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;
}
}