之前寫了一個文件讀寫相關的操作,點這里就可以看到
這里補充一個,從文件末尾開始讀取文件。
原理:首先將讀取文件的“游標”移到文件末尾,然后往回一個字節一個字節讀取,在回溯讀取的過程中,
遇到回車或者換行時,就讀取一行。
代碼如下:
/** * 從文件末尾開始讀取文件,並逐行打印 * @param filename file path * @param charset character */ public static void readReverse(String filename, String charset) { RandomAccessFile rf = null; try { rf = new RandomAccessFile(filename, "r"); long fileLength = rf.length(); long start = rf.getFilePointer();// 返回此文件中的當前偏移量 long readIndex = start + fileLength -1; String line; rf.seek(readIndex);// 設置偏移量為文件末尾 int c = -1; while (readIndex > start) { c = rf.read(); if (c == '\n' || c == '\r') { line = rf.readLine(); if (line != null) { System.out.println(new String(line.getBytes("ISO-8859-1"), charset)); } else { System.out.println(line); } readIndex--; } readIndex--; rf.seek(readIndex); if (readIndex == 0) {// 當文件指針退至文件開始處,輸出第一行 System.out.println(rf.readLine()); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (rf != null) rf.close(); } catch (IOException e) { e.printStackTrace(); } } }