阅读背景:

JAVA读取文件指定的任意一行数据_guantongtv的专栏_java从文件中读取一行数据

来源:互联网 

通过RandomAccessFile读取文件指定的任意一行数据

直接看代码

/**
 * @Description 读取文件中指定的任意一行数据
 * @Date 2020/11/9 13:31
 * @Version 1.0
 */
public class RandomReadLine {
    public static final String FILE_NAME = "D:\file\test.dat";
    /** 记录每一行开头的指针位置 */
    public static final List<Integer> POINT_LIST = new ArrayList<>();
    static{
        try(BufferedReader br = new BufferedReader(new FileReader(FILE_NAME));){
            // 记录每一行字节大小
            int lineSize = 0;
            // 记录已读取到的字节总大小
            int totoalSize = 0;
            String readLine = null;
            while ((readLine = br.readLine())!=null){
                lineSize = readLine.getBytes().length;
                POINT_LIST.add(totoalSize);
                // 每行行末有换行符故需要+1
                totoalSize += lineSize+1;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        System.out.println(readLine(3));
    }

    public static String readLine(int lineNum){
        if(lineNum <= 0 || lineNum > POINT_LIST.size()){
            throw new IllegalArgumentException(String.format("lineNum must between %s and %s",0,POINT_LIST.size()));
        }

        try (RandomAccessFile raf = new RandomAccessFile(new File(FILE_NAME),"r");){
            raf.seek(POINT_LIST.get(lineNum-1));
            byte[] bytes = raf.readLine().getBytes("ISO-8859-1");
            return new String(bytes,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
    
}/**
 



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: