国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java實現(xiàn)倒序讀取文件功能示例分享

2019-11-26 15:32:19
字體:
供稿:網(wǎng)友

Long end,long num,File file,String charset
4個參數(shù)說明
end 相當于坐標 ,tail 向上的起點,num是讀取的行數(shù),file 目標文件 charset字符集 默認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行,其實就是接著上邊的第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ù)不夠,并且沒有到達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;
    }


}

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 皮山县| 邢台市| 石嘴山市| 都昌县| 乐都县| 海伦市| 博乐市| 毕节市| 锦州市| 岳池县| 界首市| 含山县| 青铜峡市| 通城县| 同心县| 怀仁县| 五华县| 大邑县| 安顺市| 皋兰县| 南涧| 繁峙县| 承德市| 托克逊县| 榕江县| 宝丰县| 依安县| 临夏县| 恩施市| 桐梓县| 肇州县| 青岛市| 那曲县| 含山县| 桑植县| 红原县| 石阡县| 勃利县| 花莲县| 宝坻区| 泽州县|