Use RamdonAccessFile to append an object

Source: Internet
Author: User

RamdonAccessFile is a very useful class with powerful functions. You can use its length () and seek () Methods to easily append files, I believe that the following example is easy to understand. Write 10 rows first, read the length (in bytes) with length (), and use seek () to move to the end of the file, add more records and display the records.

Import java. io .*;
Public class IOStreamDemo {
Public static void main (String [] args ){
Try {
RandomAccessFile rf1 = new RandomAccessFile ("d: \ jeru.txt", "rw ");
For (int I = 0; I <10; I ++ ){
Rf1.writeBytes ("xixi, this is line" + I + "");
}
Rf1.close ();
 
Int I = 0;
String record = new String ();
RandomAccessFile rf2 = new RandomAccessFile ("d: \ jeru.txt", "rw ");
Rf2.seek (rf2.length ());
Rf2.writeBytes ("lala, append line" + "");
Rf2.close ();
  
RandomAccessFile rf3 = new RandomAccessFile ("d: \ jeru.txt", "r ");
While (record = rf3.readLine ())! = Null ){
I ++;
System. out. println ("Value" + I + ":" + record );
}
Rf3.close ();
} Catch (Exception e ){}
}
}


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.