JAVA如何实现从最后一行读取文件
import javaioFileNotFoundException;
import javaioIOException;
import javaioRandomAccessFile;
public class FromEndRF {
public static void read(String filename) {
read(filename GBK)
}
public static void read(String filename String charset) {
RandomAccessFile rf = null;
try {
rf = new RandomAccessFile(filename r)
long len = rflength()
long start = rfgetFilePointer()
long nextend = start + len ;
String line;
rfseek(nextend)
int c = ;
while (nextend > start) {
c = rfread()
if (c == \n || c == \r) {
line = rfreadLine()
if (line != null) {
Systemoutprintln(new String(linegetBytes(ISO) charset))
}else {
Systemoutprintln(line)// 输出为null可以注释掉
}
nextend;
}
nextend;
rfseek(nextend)
if (nextend == ) {// 当文件指针退至文件开始处输出第一行
Systemoutprintln(new String(rfreadLine()getBytes(ISO) charset))
}
}
} catch (FileNotFoundException e) {
eprintStackTrace()
} catch (IOException e) {
eprintStackTrace()
} finally {
try {
if (rf != null)
rfclose()
} catch (IOException e) {
eprintStackTrace()
}
}
}
public static void main(String args[]) {
read(d:\\txt gbk)
}
}