Randomaccessfile Java provides access to the contents of a file that can be read or written. Support random access to files, can access any location of the file.
1) Java File model
The file on the hard disk is a byte byte stored in byte and is a collection of data.
2) Open File
There are two modes of RW read-write R.
Randomaccessfile randomaccessfile=new randomaccessfile (file, "RW");
A file pointer that opens a file when the pointer is at the beginning of pointer=0.
3) How to write
Randomaccessfile.write (' Zhao ');//write only one byte, and the pointer points to the next position, ready to write again
4) Reading method
int B=randomaccessfile.read (...) Read a Byte
5) Be sure to close the file after reading and writing (Oracle official note)
Package com.zhao.randomAccessFile;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.RandomAccessFile;
Import Java.util.Arrays;
public class Randomaccessfiledemo {
public static void Main (string[] args) throws IOException {
File Directory=new file ("demo");
if (!directory.exists ()) {
Directory.mkdir ();
}
File File=new file (directory, "Raf.txt");
if (!file.exists ()) {
File.createnewfile ();
}
Randomaccessfile randomaccessfile=new randomaccessfile (file, "RW");
Position of the pointer
System.out.println (Randomaccessfile.getfilepointer ());
Randomaccessfile.write (' Zhao ');//write only one byte
System.out.println (Randomaccessfile.getfilepointer ());
Randomaccessfile.write (' B ');
System.out.println (Randomaccessfile.getfilepointer ());
int i=0x7ffffff;
Write one byte at a time, if I write to write 4 times
Randomaccessfile.write (i>>>24);//high 8-bit
Randomaccessfile.write (I>>>16);
Randomaccessfile.write (I>>>8);
Randomaccessfile.write (i);
System.out.println (Randomaccessfile.getfilepointer ());
Can directly write an I
Randomaccessfile.writeint (i);
System.out.println (Randomaccessfile.getfilepointer ());
String s= "Medium";
Byte[] Bytes=s.getbytes ("GBK");
Randomaccessfile.write (bytes);
System.out.println (Randomaccessfile.length ());
System.out.println (Randomaccessfile.getfilepointer ());
To read the file, you must move the pointer to the head
Randomaccessfile.seek (0);
One-time read to read the contents of a file into a byte array
Byte[] bs=new byte[(int) randomaccessfile.length ()];
Randomaccessfile.read (BS);
System.out.println (Arrays.tostring (BS));
String Ss=new string (BS);
SYSTEM.OUT.PRINTLN (ss);
Randomaccessfile.close ();
}
}
Integer.tohexstring (B&0xff) converts a byte byte array into 16 binary.
Java.io.RandomAccessFile