Randomaccessfile Java provides access to the contents of a file that can be read or written.
Randomaccessfile supports random access to files and can access any location in the file
(1) Java file model
The file on the hard disk is stored in byte byte byte and is a collection of data
(2) Open file
There are two modes of "RW" (read-write) "R" (read-only)
Randomaccessfile RAF = new Randomeaccessfile (file, "RW")
The file pointer opens the file when the pointer is at the beginning pointer = 0;
(3) How to write
Raf.write (int)---> Write only one byte (last 8 bits), while the pointer points to the next position, ready to write again
(4) Method of Reading
int b = raf.read ()---> read one byte
(5) The file must be closed after reading and writing (Oracle official note)
PackageRandomaccessfile;ImportJava.io.File;Importjava.io.IOException;ImportJava.io.RandomAccessFile;Importjava.util.Arrays; Public classrandomaccessfile{ Public Static voidMain (string[] args)throwsIOException {File demo=NewFile ("Demo"); if(!demo.exists ()) Demo.mkdir (); File File=NewFile (demo, "Raf.dat")); if(!file.exists ()) file.createnewfile (); Randomaccessfile RAF=NewRandomaccessfile (file, "RW"); System.out.println (Raf.getfilepointer ()); Raf.write (' A ');//write only one byteSystem.out.println (Raf.getfilepointer ()); Raf.write (B); intI=0x7fffffff; //Write only one byte at a time, I write it all in four timesRaf.write (i>>>24); Raf.write (i>>>16); Raf.write (i>>>8); Raf.write (i); System.out.println (Raf.getfilepointer ()); Raf.writeint (i); String s= "Lee"; byte[] Gbk=s.getbytes ("GBK"); Raf.write (GBK); System.out.println (Raf.length ()); //To read the file, you must move the pointer to the headRaf.seek (0); //one-time read to read the contents of a file into a byte array at once byte[] buf=New byte[(int) Raf.length ()]; Raf.read (BUF); System.out.println (arrays.tostring (BUF)); for(byteb:buf) {System.out.println (integer.tohexstring (b&0XFF) + ""); } raf.close (); }}
Use of the Java_randomaccessfile class