Use of the "Java IO Stream" Randomaccessfile class

Source: Internet
Author: User

Use of the Randomaccessfile class

The Randomaccessfile class is a Java-provided 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.

Randomaccessfile class Implementation steps

(1) File model

The first step is to know that 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 opening files on a file's hard disk: "RW" (Read-write), "R" (read-only). You can use the Randomaccessfile class to specify the mode in which the file is opened, such as:

New Randomaccessfile (file, "RW")

Because the Randomaccessfile class is arbitrarily accessible anywhere in the file, it is essentially because the Randomaccessfile class provides a file pointer.

The file pointer opens the file when the pointer is at the beginning pointer = 0;

(3) Basic writing method

The Randomaccessfile class provides a basic writing method, write (), which is an example of a write-shaping int:

Raf.write (int)---> Write only one byte (last 8 bits), while the pointer points to the next position, ready to write again

Note: The write () method can only write one byte at a time for types other than bytes, such as to write to an int type completely, using the Write () Method 4 times. However, you can write directly to a byte array, such as write (byte[]).

(4) Basic reading method

The Randomaccessfile class provides a basic reading method read (), with the same usage as write ():

int b = raf.read ()---> read-only one byte

(5) Close the stream

It is important to close the stream after the file is read and written (Oracle official note), which can produce unexpected exceptions if not turned off!

Use cases for the Randomaccessfile class

The basic Randomaccessfile class usage steps are described above, and then I'll write a case to implement these steps.

1. First create test directories and files under the project

1 New File ("demo"); 2         if (! demo.exists ()) {3            demo.mkdirs (); 4         }5         file file=new file (demo, "Raf.txt"); 6         if (! file.exists ()) {7            file.createnewfile (); 8         }

2. Initialize the Randomaccessfile class, open the file you just created, and view the location of the file pointer

1 randomaccessfile raf=new randomaccessfile (file, "RW"); 2         // position of the pointer 3         System.out.println (Raf.getfilepointer ());

3. Using the Randomaccessfile class to write an int type variable

1 intI=0X7FFFFFFF;//the largest integer2         //Write only one byte at a time, if I write it, I have to write it 4 times .3Raf.write (i>>>24);//8-bit high4Raf.write (i>>>16);5Raf.write (i>>>8);6 Raf.write (i);7         //can also directly use the Writeint () method, directly written, the principle of this method ibid.8Raf.writeint (i);

The principle of the Writeint () method is also done using the Write () method, similar to the write () method I wrote:

4. Writing string strings using the Randomaccessfile class

Define a string s

String s= "Chinese";

1) First convert the string to a byte array, and then write the array

1 byte [] Gbk=s.getbytes ("Utf-16be"); 2 raf.write (GBK);

Note: Here the encoding format to press UTF-16BE, because the Java internal encoding format is this, otherwise read out will be garbled. Read more about coding issues in my other article, "Coding Problems in Computers"

2) using the WriteChars () method

Raf.writechars (s);

Principle: WriteChars () is called by the Writechar () method to write the characters of the string s into the file, while the contents of the Writechar () code are as follows (essentially, the write () method writes each byte):

5. read out the contents of the file using the Randomaccessfile class

1//read operation, the pointer must be moved to the head2Raf.seek (0);3         //Disposable Read4         byte[] buf=New byte[(int) Raf.length ()];5 Raf.read (BUF);6System.out.println (arrays.tostring (BUF));//print out a byte array7         //Convert a byte array to a string8String s1=NewString (buf, "Utf-16be");9     TenSystem.out.println (S1);

Operation Result:

The preceding garbled is the type of int that was written, because the read-out is the encoded format of the string, so the int type is not recognized. If you want to read the int type, you have to use the Readint () method to read the int variable. In addition, the Randomaccessfile class also provides a way to read and write various types of methods, using a similar method, which is no longer elaborated here, interested friends can try on their own.

Attention:

    • If you want to start reading from the file header, you must move the pointer to the head and seek () to assign the pointer to a position;
    • Read (byte[]) can pass through the byte array to which all the bytes are reading;
    • When a byte array is converted to a string, the encoding format of the primary string is the same as the encoding format when the byte is written, otherwise garbled.
    • Each time you write and read, the position of the file pointer changes, using the position of the pointer, if necessary.

6. Close the Randomaccessfile class

Use the Randomaccessfile class must not forget to close the flow, very important, to form a good habit!!

// Finally, the Raf.close () must be closed ;

Digression: I mentioned an interesting int in this article, which is the largest int type in Java. Why does 0X7FFFFFF represent the largest int value?

Doubts:

Each hexadecimal number is 4bit, so 8-bit hexadecimal equals 32bit (4 bytes), which is exactly an int integer.

The binary code for F is 1111

7 Binary code is 0111

In this way, the binary representation of the whole integer 0x7FFFFFFF is except that the first is 0 and the rest is 1. That is, this is the largest integer int (because the first bit is the sign bit, and 0 indicates that it is a positive number).

Use of the "Java IO Stream" Randomaccessfile class

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.