我从网上找了个倒序读取文件的代码,我自己测试读自己创建的文件,可以读出内容,但是读真正生成的日志文件,读出的都是空字符串,程序没有报错。
个人测试了应该是和文件内容有关,但找不出原因所在,代码如下:
package cn.cmts.control.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
-
http://bbs.csdn.net/topics/190181198 从最后一行开始读取
/
public class test {
/*
*- @param filename
- 目标文件
- @param charset
- 目标文件的编码格式 */ public static void read(String filename, String charset) { RandomAccessFile rf = null; try { rf = new RandomAccessFile(filename, "r"); long len = rf.length(); long start = rf.getFilePointer(); long nextend = start + len - 1; String line; rf.seek(nextend); int c = -1; int count =0; while (nextend > start) { c = rf.read(); if (c == '\n' || c == '\r') { line = rf.readLine(); if (line != null) { String info = new String(line.getBytes("ISO-8859-1"), charset); count+=1; System.out.println(count); if (info.contains("是的")) { System.out.println(count+":::"+new String(line.getBytes("ISO-8859-1"), charset)); break; } if (count>100) { break; } } else { System.out.println(line); } nextend--; } nextend--; rf.seek(nextend); if (nextend == 0) {// 当文件指针退至文件开始处,输出第一行 // System.out.println(rf.readLine()); System.out.println(new String(rf.readLine().getBytes("ISO-8859-1"), charset)); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (rf != null) rf.close(); } catch (IOException e) { e.printStackTrace(); } } }
public static void main(String args[]) throws FileNotFoundException {
read("e:\apache-tomcat-8.5.13-windows-x64\apache-tomcat-8.5.13\logs\localhost_access_log.2017-04-21.txt", "GB2312");
}
}