1. 程式人生 > >讀取檔案最後一行資料

讀取檔案最後一行資料

使用RandomAccessFile , 從後找最後一行資料

public static String readLastLine(File file) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    long len = raf.length();
    String lastLine = "";
    if (len != 0L) {
        long pos = len - 1;
        while (pos > 0) {
            pos--;
            raf.seek(pos);
            if
(raf.readByte() == '\n') { lastLine = raf.readLine(); break; } } } raf.close(); return new String(lastLine); }

使用RandomAccessFile , 從後找最後n行資料

RandomAccessFile raf = null;
File tf = new File(“PATH\OF\THE\DOCUMENT”);
if (tf.exists() && tf.canRead()) {
raf = new RandomAccessFile(tf, “r”);
long len = raf.length();
long pos = len - 1;
if (len > 0L) {
int l = 0;
while (pos > 0 && l < n) {
pos–;
raf.seek(pos);
if (raf.readByte() == ‘\n’) {
l = l + 1;
}
}
}
}
byte[] bytes = new byte[(int) (len - pos)];
raf.read(bytes);
String lines = new String(bytes, “utf-8”);
String[] split = lines.split(“\n”);//split就是最後6行的資料