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 ){}
}
} |