Java-IO stream RandomAccessFile class, iorandomaccessfile
RafDemo. java
Package com. test. io; import java. io. file; import java. io. IOException; import java. io. randomAccessFile; import java. util. arrays; public class RafDemo {public static void main (String [] args) throws IOException {File demo = new File ("demo"); if (! Demo. exists () {demo. mkdir ();} File file = new File (demo, "raf. dat"); if (! File. exists () {file. createNewFile ();} RandomAccessFile raf = new RandomAccessFile (file, "rw"); System. out. println (raf. getFilePointer (); raf. write ('A'); // A char occupies two bytes, but write only writes one byte at A time (the last eight digits of the character) System. out. println (raf. getFilePointer (); raf. write ('B'); int I = 0x7fffffff; raf. write (I >>> 24); // write the high eight-bit raf of I. write (I >>> 16); raf. write (I> 8); raf. write (I); System. out. println (raf. getFilePointer (); // write an int raf directly. writeInt (I); String s = "you"; byte [] B = s. getBytes ("utf8"); raf. write (B); System. out. println (raf. length (); // read the file. The pointer must be moved to the raf header. seek (0); // One-time read, read all the content in the file to byte [] buf = new byte [(int) raf in the byte array. length ()]; raf. read (buf); System. out. println (Arrays. toString (buf); for (byte c: buf) {System. out. print (Integer. toHexString (c & 0xff) + "") ;}// close the file raf. close ();}}
Execution result:
01613[65, 66, 127, -1, -1, -1, 127, -1, -1, -1, -28, -67, -96]41 42 7f ff ff ff 7f ff ff ff e4 bd a0