public class Test {
public static void main(String[] ages) throws IOException {
File file = new File("test.txt");
String readLastLine = readLastLine(file, "UTF-8");
System.out.println(readLastLine);
}
public static String readLastLine(File file, String charset) throws IOException {
if (!file.exists() || file.isDirectory() || !file.canRead()) {
return null;
}
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "r");
long len = raf.length();
if (len == 0L) {
return "";
} else {
long pos = len - 1;
while (pos > 0) {
pos--;
raf.seek(pos);
if (raf.readByte() == '\n') {
break;
}
}
if (pos == 0) {
raf.seek(0);
}
byte[] bytes = new byte[(int) (len - pos)];
raf.read(bytes);
if (charset == null) {
return new String(bytes);
} else {
return new String(bytes, charset);
}
}
} catch (FileNotFoundException e) {
} finally {
if (raf != null) {
try {
raf.close();
} catch (Exception e2) {
}
}
}
return null;
}
}
使用RandomAccessFile直接将指针移到文件最后一个字符开始读取,从后往前读取,当遇到第一换行符时结束
不给你找具体代码了,给你一个思路吧。
打开文件,读的时候从文件末尾从后往前读,一次读若干字节,然后从后往前判断,如果遇到行尾,就中止,这样就拿到最后一行了,而且开销很小。
Scanner sc=new Scanner(new FileReader("D:\\text.txt"));
String line=null;
while((sc.hasNextLine()&&(line=sc.nextLine())!=null)){
if(!sc.hasNextLine())
System.out.println(line);
}