Import? Java . io . file not found exception; ?
Import? Java . io . io exception; ?
Import? Java . io . random access file; ?
/**?
*? Start reading from the last line?
*/?
Public? Class? FromEndRF? {?
/**?
*?
*? @param? File name? Target file?
*? @param? Character set? What is the encoding format of the target file?
*/?
Public? Static electricity Invalid? Read (string? File name? String? Character set)? {?
RandomAccessFile? rf? =? null?
Try it? {?
rf? =? New? RandomAccessFile (file name, "r"); ?
Dragon? Ryan. =? rf.length()。 ?
Dragon? Start? =? RF . getfile pointer(); ?
Dragon? nextend? =? Start? +? Ryan. -? 1; ?
String? Line; ?
RF . seek(next end); ?
int? c? =? - 1; ?
What time? (nextend? & gt? Start)? {?
c? =? RF . read(); ?
What if? (c? ==? \n '? ||? c? ==? \r ')? {?
Line? =? RF . readline(); ?
What if? (line? ! =? null)? {?
System.out.println (new? String (line?
. getBytes("ISO-8859- 1 "),? charset)); ?
}? Or what? {?
system . out . println(line); ?
}?
next end-; ?
}?
next end-; ?
RF . seek(next end); ?
What if? (nextend? ==? 0)? {//? When the file pointer returns to the beginning of the file, the first line is output.
//? 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 it? {?
What if? (rf? ! =? null)?
RF . close(); ?
}? Catch? (IOException? e)? {?
e . printstacktrace(); ?
}?
}?
}?
Public? Static electricity Invalid? Main (string? args[])? {?
read("mynewfile.txt ",“UTF-8”); ?
}?
Description: The above is a case of reading a document backwards. You can design your own code according to this case and your actual needs. In addition, if it is a web application or other persistent application, you can try to keep the file open by using a separate thread or storing the read location in memory.