Source: Java reads the last n rows of a file
Source code: Http://www.zuidaima.com/share/1550463669226496.htm
Specify the number of rows you can get to all lines from this line to the end of the file, sharing the ego bear.
Source file:
Read the last 10 rows of results
Import Java.io.file;import java.io.ioexception;import Java.io.randomaccessfile;import Java.util.ArrayList;import java.util.list;/** * * File Read class * * @author Big Bear www.zuidaima.com * @version [1.0, 2013-7-24] * @since [interview/1.0] */public c Lass readfile{//main function, program entry public static void main (string[] args) {//Call read method, define file and read number of rows READLASTN Line (New File ("D:\\apache-tomcat-7.0.40\\running.txt"), 10L); }/** * Read the last n rows of the file * * The current number of rows according to the newline character, * use statistics to determine the current read nth row * PS: The output list is flashbacks, need to reverse the output of the list * * @param files to file * @param numread number of rows read * @return list<string> */public static list<string& Gt Readlastnline (file file, long Numread) {//define result set list<string> results = new arraylist<string> (); Number of rows statistics Long Count = 0; Exclude unreadable State if (!file.exists () | | file.isdirectory () | |!file.canread ()) {return null; }//Using Random Read Randomaccessfile fileRead = null; try {//use read mode FileRead = new Randomaccessfile (file, "R"); Read file length long = Fileread.length (); If 0, represents an empty file, directly returns an empty result if (length = = 0L) {return result; } else {//initialize cursor long pos = length-1; while (pos > 0) {pos--; Start reading Fileread.seek (POS); If read to \ n means read to a line if (fileread.readbyte () = = ' \ n ') {//Use Read Line gets the current row String = Fileread.readline (); Save result Result.add (line); Prints the current row System.out.println (line); Row count, if the number of rows specified by the Numread is reached,Jump out of the loop 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 { Close resource Fileread.close (); } catch (Exception e) {}}} return result; }}
Java reads the last n rows of a file