美文网首页
Java从后向前读取TXT文件

Java从后向前读取TXT文件

作者: NightingCrow | 来源:发表于2019-03-08 17:29 被阅读0次

    /**

    * 读取最后几行

    *

    * @param file    文件

    * @param charset  编码

    * @param n        条数

    * @param positive 是否正序

    * @return ArrayList<String>

    */

    public static ArrayList<String> tail(File file, int n, Charset charset, boolean positive) {

        ArrayList<String> arrayList = new ArrayList<>();

        RandomAccessFile randomAccessFile = null;

        try {

            randomAccessFile = new RandomAccessFile(file, "r");

            //获取文件长度

            long length = randomAccessFile.length();

            //如果长度小于1,则说明文件为空

            if (length < 1) {

                return arrayList;

            }

            long available = length - 1;

            //标记文件最后位置

            randomAccessFile.seek(available);

            for (int i = 0; i < n && available > 0; i++) {

                if (available == length - 1) {

                    available--;

                    randomAccessFile.seek(available);

                }

                int c = randomAccessFile.read();

                while (c != '\n' && available > 0) {

                    available--;

                    randomAccessFile.seek(available);

                    c = randomAccessFile.read();

                }

                //标记当前位置

                long nowPointer = randomAccessFile.getFilePointer();

                String line = new String(randomAccessFile.readLine().getBytes(), charset);

                arrayList.add(line);

                if (nowPointer > 1) {

                    randomAccessFile.seek(nowPointer - 2);

                }

            }

            if (!positive) {

                Collections.reverse(arrayList);

            }

            return arrayList;

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            try {

                assert Objects.nonNull(randomAccessFile);

                randomAccessFile.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return arrayList;

    }

    相关文章

      网友评论

          本文标题:Java从后向前读取TXT文件

          本文链接:https://www.haomeiwen.com/subject/wyqdpqtx.html