Requirement: In the process of generating the log file, the log needs to be read in real time, the location of the read is recorded once per read, and the next time it is read from that location
Reference: http://sunnylocus.iteye.com/blog/694666
Problem: Since I stopped every time I read dozens of rows of logs, if I use the above connected code randomaccessfile.length () to record the location of the file, I find that the record is much larger than the location of the read, which leads to the loss of some information
Method 1: Because the log is always written, starting from 0, you can first record the current reading position of the pointer, the next time you start to read from the place again
Method 1 needs to use the following:
Randomaccessfile.getfilepointer ()
This method returns the offset from the beginning of the file, in bytes, of the current position
Randomaccessfile.readline ()
method to read the next line of text from this file. The method starts at the byte read from the file, starting at the current file pointer until it reaches the end of a line or at the end of the file. Each byte is converted to a character by taking a byte of the value of the low 8-bit character and setting the high 8-bit character to 0.
Randomaccessfile.seek ()
The offset position, measured in bytes from the beginning of the file, on which to set the file pointer.
Randomaccessfile.length ()
This method returns the length of the current file, in bytes.
File LogFile = new file ("D:\\workspace\\drawchart\\src\\read_log\\log.txt");
Private long lasttimefilesize = 0; Last File size
protected voidDoPost (httpservletrequest request,httpservletresponse response)throwsservletexception, ioexception{//gets the location of the last read that was savedString str = request.getparameter ("Lasttimefilesize"); Lasttimefilesize=Long.parselong (str); System.out.println (lasttimefilesize); Try { LongLen =logfile.length (); System.out.println (len); if(Lasttimefilesize >=Len) {Lasttimefilesize=Len; Try { //if the read speed exceeds the write speed, wait 5 secondsThread.Sleep (5000); } Catch(interruptedexception E1) {e1.printstacktrace (); } }Else{randomaccessfile Randomfile=NewRandomaccessfile (LogFile, "R"); Randomfile.seek (lasttimefilesize); String tmp=NULL; while(TMP = Randomfile.readline ())! =NULL) { if(Matcher0.lookingat ()) {if(flag==4){ //record the location of the read fileLasttimefilesize =Randomfile.getfilepointer (); System.out.println (lasttimefilesize); Save Pointer } } } Catch(IOException e) {e.printstacktrace (); }finally{ //Other Operations } }
Method 2: Record line numbers
-If you use a cyclic read method, the cycle consumes resources and makes the system too heavy
Read log files in real time