Reads content anywhere in the file-RandomAccessFile

Source: Internet
Author: User

  Background: Our company only needs to update online programs at two time points every week, so there will be a lot of O & M personnel at those two time points. After updating the program, we need to verify that if the new function reports an error at this time, we can only view the console log information through the O & M personnel, because there are many people, finding someone to call up the log information becomes a very troublesome task. Furthermore, the error log output cannot be found, which is not conducive to the development of debugging programs. For this reason, I made a page to read log output from the console.

Considering that the log file may be very large, if I read it at a time, the memory overhead and response speed will be completely compromised, so I use java. io. randomAccessFile class, which can read the file content at any position by controlling the pointer position.

/*** Read weblogic console logs by page * @ param logFileName log file name * @ param curPage: the page number of the currently read content. The file is read from the end, the page number at the end is 1 * @ param row the number of lines read each time * @ param charSet the character encoding of the read content * @ param session * @ param model * @ return */@ RequestMapping ("viewConsoleLog ") @ ResponseBody public String viewConsoleLog (@ RequestParam (required = false, defaultValue = "nohup. out ") String logFileName, @ RequestParam (required = false, defaultValue =" 1 ") Int curPage, @ RequestParam (required = false, defaultValue = "500") int row, @ RequestParam (required = false, defaultValue = "GBK") String charSet, HttpSession session, model model) {String rootPath = session. getServletContext (). getRealPath ("/"); List <String> list = new ArrayList <String> (); RandomAccessFile logFile = null; try {File rootDir = new File (rootPath ); file binDir = new File (rootDir. get ParentFile (), "bin"); // open the log File logFile = new RandomAccessFile (new File (binDir, logFileName), "r") in read-only mode "); // calculate the row number to be read and start from the last row. Therefore, the row number at the end is 0 int startRow = (curPage-1) * row; int endRow = curPage * row-1; // The current row number int curRow = 0; // obtain the file size long len = logFile. length (); // read the String line = null; if (len> 0) {// locate to the end of the file long p = len; while (p --> 0) {logFile. seek (p); // locate the pointer position if (curRow> endRow) {// if the number of read rows reaches If (logFile. readByte () = '\ n') {if (curRow> = startRow & curRow <= endRow) {line = logFile. readLine (); // read the line break. The line break here is the line break of the previous line. So the line = (line = null) of the first line will never be printed here )? "": New String (line. getBytes ("ISO-8859-1"), charSet); // if it is a line break and within the specified row number, read the row; if it is empty, it prints the empty row list. add (line) ;}currow ++; // if it is not in the specified row number, skip reading. }}// read the first row of the file curRow ++; if (curRow> = startRow & curRow <= endRow) {logFile. seek (0); // locate the pointer to line = logFile at the beginning of the file. readLine (); // read the line break. The line break here is the line break of the previous line. So the line = (line = null) of the first line will never be printed here )? "": New String (line. getBytes ("ISO-8859-1"), charSet); // if it is a line break and within the specified row number, read the row; if it is empty, it prints the empty row list. add (line);} if (list. size () = 0) {// No data is read, indicating that all content models have been loaded. addattriver ("isOver", true) ;}} catch (FileNotFoundException e) {e. printStackTrace (); model. addAttribute ("msg", "Log File not found:" + logFileName);} catch (IOException e) {e. printStackTrace (); model. addAttribute ("msg", "failed to read Log File:" + logFile Name);} finally {try {if (logFile! = Null) logFile. close ();} catch (IOException e) {e. printStackTrace () ;}} model. addAttribute ("content", list); model. addAttribute ("curPage", curPage); return new Gson (). toJson (model );}View Code

This function is used to query log information by page. It reads log information in reverse direction from the end of the log file. the backend is developed based on the spring mvc framework. This method returns a json object through ajax requests.

Json data has been transferred to the front-end, which is simple. The front-end code will not be displayed here.

  Summary:

1. constructor: RandomAccessFile has two constructor methods.

(1)RandomAccessFile(File file, String mode)

(2)RandomAccessFile(String filepath, String mode)

The mode parameter indicates the file opening method. Its value and meaning are as follows:

Value

Meaning

"R" Open in read-only mode. AnyWriteMethods will throwIOException.
"Rw" Open for reading and writing. If the file does not exist, try to create it.
"Rws" Open for reading and writing,"Rw"Also, every update to the file content or metadata must be synchronized to the underlying storage device.
"Rwd" Open for reading and writing,"Rw"Also, every update to the file content is synchronized to the underlying storage device.

2. File length attributes: Same as java. io. File objectsLength

3. pointer locating method:

Public voidSeek(Long pos) throws IOException {}
    Parameterspos-Set the file pointer at the offset measured in bytes starting with a file.

(1) The pos is located between [0, length], and an error is returned if the range is exceeded;

(2) Generally, do not point the pos to the length when reading the file, because the point of the pos to The length indicates that the file has been read, and then calling the read method will throw an exception, you can set pos = length-1, which indicates the last character of the next read operation;

(3) Multiple read methods are defined to read different types of data. For details, refer to the API

4. When reading filesNote pointer position:

(1) Automatic pointer movement: each time read is called, the pointer pos automatically moves to the read data, which means that if you need to read a piece of data repeatedly, the seek (pos) method should be manually called before each read;

(2) For reverse reading, Note: I use if (logFile. readByte () = '\ n') {} to determine whether the linefeed is read. Due to the (1) relationship, after executing the if statement, the pointer moves backward to a byte length, therefore, in the if block, we can directly call readLine to obtain the data of the next row. Because of this, in this if block, only the data with the linefeed '\ n' can be obtained. This indicates that the data in the first row will never be obtained, there is no line break '\ n'), so here the first line of data is read separately.

(3) empty row processing: line = logFile. readLine (); If empty rows are read, line = null here. (I think this is not correct. The reason is simple: Since it is empty rows, it indicates that this row exists, but there is no data, so I personally think it should be "" rather than null); so here do not directly use line, be careful to report NullPointException;

(4) Character Set Problem: readLine () has Chinese garbled characters. I have not studied whether to directly read Chinese characters. Here, I simply process the read results, if you have a better solution for Chinese Garbled text, please leave a message to me.

  

Reprinted please indicate the source: http://www.cnblogs.com/Sunw/p/3801145.html

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.