Java-IO stream RandomAccessFile class, iorandomaccessfile

Source: Internet
Author: User

Java-IO stream RandomAccessFile class, iorandomaccessfile

  • RandomAccessFile

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  

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.