Reading files from the last line in java line by line

Source: Internet
Author: User

Public static void main (String [] args ){
Try {
// Write the file first and append it to the end of the file. If the file does not exist, the file is automatically created.
FileWriter fw = new FileWriter ("C:/test.txt", true); // use FileWriter to open the file
PrintWriter pw = new PrintWriter (fw); // load the file with a write pointer
String [] str = {""}; // String to be written
For (String index: str ){
Pw. println (index); // append each time to the end of the file
}
Pw. close (); // close
Fw. close (); // close
 
// Locate the last row of the file below and read one row at the top
RandomAccessFile raf = new RandomAccessFile ("C:/test.txt", "r"); // This class can locate the file,
// Java
// The unique IO class that can be located
Long len = raf. length (); // get the object length to locate the end
If (len <= 3) {// checks whether the file is empty.
System. out. println ("the flie is NULL! ");
Return;
}
Long pos = len-1; // locate the end Of the file
While (pos> 0) {// determines whether the object has reached the header
-- Pos; // forward pointer of one character and one character
Raf. seek (pos); // locate the position indicated by the file pointer
If (raf. readByte () = '\ n') {// if it is a line break, you can read this line.
System. out. println (raf. readLine ());
}
}
Raf. seek (pos); // Finally, read the first row
System. out. println (raf. readLine ());
Raf. close (); // close
 
} Catch (FileNotFoundException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
System. exit (0 );
Return;
}

Related Article

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.