Android工具类(分段读取text文件内容)


import com.inks.inkslibrary.Utils.L;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;


public class ReadTextUtil {

    private RandomAccessFile readFile;
    private long pages = 0;//总页数
    private int pageSize;//每一页的字节数 字节数固定
    private long bytesCount;//字节总数
    private boolean isFile = true;

    private String filePath;


    /**
     * @param filePath 文件路径
     * @param pageSize 每一页字节大小
     * @return
     * @method
     * @description
     * @date: 2020/3/31 9:27
     */
    public ReadTextUtil(String filePath, int pageSize) {
        this.pageSize = pageSize;
        this.filePath = filePath;
        readText();
    }

    private void readText(){
        File file = new File(filePath);
        try {
            readFile = new RandomAccessFile(file, "r");
            isFile = true;
            try {
                bytesCount = readFile.length();//获得字节总数
            } catch (IOException e) {
                e.printStackTrace();
                L.e("ReadTextUtil:获取字节数失败");
            }
            L.e("ReadTextUtil文件总字节数"+bytesCount);
            pages = (long) Math.ceil(bytesCount / (float)pageSize);//计算得出文本的页数
            L.e("ReadTextUtil文件页数"+pages);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            isFile = false;
            L.e("ReadTextUtil:未发现文件");
        }
    }

    public long getPages() {
        return pages;
    }

    public void refresh(){
        close();
        readText();
    }

    //上一页功能的实现
    public String getText(long page,String format) {
        String content = "读取异常";
        //第一页 的情况 定位在0字节处 读取内容 当前页数不改变
        seek(page);
        try {
            content = read(format);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    public void close(){
        try {
            readFile.close();
            readFile = null;
        } catch (IOException e) {
            e.printStackTrace();
            readFile = null;
        }
    }

    //定位字节位置 根据页数定位文本的位置
    //page   1到最后一页
    private void seek(long page) {
        try {
            //if(pages)
            readFile.seek((page - 1) * pageSize);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private String read(String format) throws IOException{
        //内容重叠30 防止末尾字节乱码
        byte[] chs = new byte[pageSize + 30];
        readFile.read(chs);
        return new String(chs, Charset.forName(format));
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值