/**
* 讀取最后幾行
*
* @param file? ? 文件
* @param charset? 編碼
* @param n? ? ? ? 條數(shù)
* @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;
}