1. 程式人生 > >java讀取檔案後n行

java讀取檔案後n行

public class ReadFile {
    //Main函式,程式入口
public static void main(String[] args) {
        //呼叫讀取方法,定義檔案以及讀取行數
List<String> list = readLastNLine(new File("D:/1.txt"), 5L);
        if (list != null) {
            for (String str : list) {
                System.out.println(str + "<br>");
}
        }
    }

    /**
* 讀取檔案最後N行 * <p> * 根據換行符判斷當前的行數, * 使用統計來判斷當前讀取第N行 * <p> * PS:輸出的List是倒敘,需要對List反轉輸出 * * @param file 待檔案 * @param numRead 讀取的行數 * @return List<String> */ public static List<String> readLastNLine(File file, long numRead) { // 定義結果集
List<String> result = new ArrayList<String>(); //行數統計 long count = 0; // 排除不可讀狀態 if (!file.exists() || file.isDirectory() || !file.canRead()) { return null; } // 使用隨機讀取 RandomAccessFile fileRead = null; try { //使用讀模式 fileRead = new RandomAccessFile(file, "r"
); //讀取檔案長度 long length = fileRead.length(); //如果是0,代表是空檔案,直接返回空結果 if (length == 0L) { return result; } else { //初始化遊標 long pos = length - 1; while (pos > 0) { pos--; //開始讀取 fileRead.seek(pos); //如果讀取到\n代表是讀取到一行 if (fileRead.readByte() == '\n') { //使用readLine獲取當前行 String line = new String(fileRead.readLine().getBytes("ISO-8859-1"), "utf-8"); //儲存結果 result.add(line); //列印當前行 //System.out.println(line); //行數統計,如果到達了numRead指定的行數,就跳出迴圈 count++; if (count == numRead) { break; } } } if (pos == 0) { fileRead.seek(0); result.add(fileRead.readLine()); } } } catch (IOException e) { e.printStackTrace(); } finally { if (fileRead != null) { try { //關閉資源 fileRead.close(); } catch (Exception e) { } } } Collections.reverse(result); return result; } }