借鉴其他博客上的方法,自己整理了一个倒序读取最新文件的方法,如有侵权则删除。
public Map<String,String> read(String fileName ) {
// 获取最新改动的文件名
File path = new File(fileName);
if (path.exists()) {
// 列出该目录下所有文件和文件夹
File[] files = path.listFiles();
// 按照文件最后修改日期倒序排序
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File file1, File file2) {
return (int) (file2.lastModified() - file1.lastModified());
}
});
fileName += files[0].getName();
}
Map<String, String> map = new HashMap<String, String>();
File file = new File(fileName);
if (file.exists()) {
RandomAccessFile rf = null;
try {
rf = new RandomAccessFile(fileName, "r");
long len = rf.length();
long start = rf.getFilePointer();//返回此文件当前偏移量
long nextend = len + start - 1;
rf.seek(nextend); //设置偏移量为文件末尾行
String line;
int c = -1;
while (nextend > start) {
c = rf.read();
if (c == '\n' || c == '\r') { //只有行与行之间才有\r\n,这表示读到每一行上一行的 末尾的\n,而执行完read后,
//指针指到了这一行的开头字符
line = rf.readLine();
if (line != null) {
if (line.contains("string")) { //判断获取的line
line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
}
nextend--;
}
}
nextend--;
rf.seek(nextend);
if (nextend == 0) { //读取到第一行时
rf.seek(0); //不需要为下次做准备了,但是因为read()方法指针从0到了1,需重置为0
line = rf.readLine();
if (line != null) {
if (line.contains("Heart") || line.contains("Carcheck")) {
line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (rf != null) {
rf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
return map;
}