- Java provides access to the contents of a file that can read files or write files.
- Support random access to files, can access any location of the file.
- Java file model, the file on the hard disk is a byte byte stored in Byte, is a collection of data
- Open file, there are two modes, "RW" read-write, "R" read-only, Randomaccessfile RAF = new Randomaccessfile (file, "RW");, file pointer, open the file pointer at the beginning point = 0;
- Write method, Raf.write ()-Write only one byte (last eight bits), and the pointer points to the next position, ready to write again
- Read method, int b = Raf.read () and read a byte
- The file must be closed after reading and writing (Oracle official note)
Rafdemo.java
PackageCom.test.io;ImportJava.io.File;Importjava.io.IOException;ImportJava.io.RandomAccessFile;Importjava.util.Arrays; Public classRafdemo { 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 ');//One char takes two bytes, but write writes only one byte at a time (the last eight bits of the A character)System.out.println (Raf.getfilepointer ()); Raf.write (B); inti = 0x7fffffff; Raf.write (i>>> 24);//write high eight bits of IRaf.write (i >>> 16); Raf.write (i>> 8); Raf.write (i); System.out.println (Raf.getfilepointer ()); //write directly to an intRaf.writeint (i); String s= "You"; byte[] B =s.getbytes ("UTF8"); Raf.write (b); 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 byte[] buf =New byte[(int) Raf.length ()]; Raf.read (BUF); System.out.println (arrays.tostring (BUF)); for(bytec:buf) {System.out.print (integer.tohexstring (c& 0xff) + ""); } //Close FileRaf.close (); }}
Execution Result:
0 1 6 - [127,1,-1,-1127,-1 ,-1,-1,-- ----- 7f FF FF FF 7f FF FF FF e4 BD A0
Java-io Stream Randomaccessfile Class