public class ReadFile {
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>");
}
}
}
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();
if (length == 0L) {
return result;
} else {
long pos = length - 1;
while (pos > 0) {
pos--;
fileRead.seek(pos);
if (fileRead.readByte() == '\n') {
String line = new String(fileRead.readLine().getBytes("ISO-8859-1"), "utf-8");
result.add(line);
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;
}
}