Java实现tail n功能

Java实现tail n功能

使用RandomAccessFile随机读取功能,从文件末尾一次读取若干个字节,然后转成字符串,存储在结果中,下次往前递推,读取够n行,或者文件读取完毕结束

import java.io.IOException;
import java.io.RandomAccessFile;

public class Tailing {
    public static void main(String[] args) throws IOException {
        System.out.println(tail("D:/a.txt", 12));
    }

    public static String tail(String file, int n) throws IOException {
        RandomAccessFile accessFile = new RandomAccessFile(file, "r");
        long total = accessFile.length();
        int bath = 128;
        int curN = 0;
        StringBuilder result = new StringBuilder();
        long pos = total - 1;
        while (curN < n && pos > 0) {
            byte[] bytes = new byte[bath];
            pos = pos - bath;
            pos = pos < 0 ? 0 : pos;
            accessFile.seek(pos);
            accessFile.read(bytes, 0, bath);

            String lines = new String(bytes, "UTF-8");
            String[] split = lines.split("\n");
            if (!lines.endsWith("\n") && curN > 0) {
                curN--;
            }
            int accept = n - curN;
            int length = split.length;
            if (accept < length) {
                for (int i = length - 1; i >= length - accept; i--) {
                    if (i < length - 1) {
                        result.insert(0, "\n");
                    }
                    result.insert(0, split[i]);
                }
                curN = n;
            } else {
                curN += split.length;
                result.insert(0, lines);
            }
        }

        try {
            accessFile.close();
        } catch (Exception ignore) {

        }

        return result.toString();
    }
}

你可能感兴趣的:(Java)