Java Io2:randomaccessfile

Source: Internet
Author: User

Randomaccessfile

The Randomaccessfile class is the most versatile file access class in the Java language, and it provides a number of file access methods. The Randomaccessfile class supports "random Access", which allows you to jump to and read data from anywhere in the file. To access a file, you do not want to read the file from the beginning to the end, but rather like access to a database as a text file, using the Randomaccessfile class is the best choice.

There is a positional indicator in the Randomaccessfile object class that points to the current read and write location, and when n bytes are read and written, the file indicator points to the next byte of the N-word section. When you first open a file, the file indicator points to the beginning of the file, you can move the file indicator to a new location, and then the read and write will start at the starting point.

The Randomaccessfile class has a great advantage in the random (relative to sequential) reading of a file, but the class is limited to manipulating files and cannot access other IO devices such as networks, memory images, and so on.

Randomaccessfile Construction Method

The Randomaccessfile class provides two ways to construct a user:

1, randomaccessfile (file file, String mode)

2, Randomaccessfile (string name, string mode)

In fact, the second construction method is also a new file to call the first method of construction, it is recommended to use the first construction method, because the first article said that file is the basis of Io, there is a file can not only through the randomaccessfile to manipulate files, You can also manipulate files by using the file object. As for Mode,java, four types of mode are available to developers:

1, "R", means open as read-only, and any write method that invokes the resulting object will cause the IOException to be thrown

2, "RW", open for Read and write, if the file does not already exist, try to create the file

3. "RWS", open for reading and writing, also requires that each update to the file content or metadata be synchronously written to the underlying storage device, relative to "RW"

4, "RWD", open for reading and writing, in contrast to "RW", also requires that each update of the file content is synchronously written to the underlying storage device

Note that the 2nd "RW" mode, the interpretation of the RW mode means that Java does not insist that a certain file exists under the specified path, if the file does not exist, it will automatically create

Methods in the Randomaccessfile

There are some common methods in Randomaccessfile:

1. void Close ()

Important, close this random access file stream and free all system resources associated with the stream

2, FileChannel Getchannel ()

Returns the unique FileChannel object associated with this file, which NiO uses to

3, Long Getfilepointer ()

Returns the current offset in this file

4, long Length ()

Returns the length of this file

5, int read ()

Read a byte of data from this file

6, int read (byte[] b)

Reads a maximum of b.length bytes from this file into a byte array, returns the total number of bytes read in, and returns 1 if there are no more data since the end of the file has been reached. This method is blocked until at least one input byte is available

7, int read (byte[] b, int off, int len)

Reads up to Len data bytes from the specified initial offset of this file into a byte array

8. Boolean Readboolean ()

Read a Boolean from this file, the rest of ReadByte (), ReadChar (), readdouble (), and so on

9. String ReadLine ()

Reads the next line of text from this file

10. Void Seek (Long POS)

Important, set the file pointer offset measured to the beginning of this file, where the next read or write operation occurs at that location

11, int skipbytes (int n)

Important, try skipping the input n bytes to discard the skipped bytes, returning the number of bytes skipped

12. Void Write (byte[] b)

Writes B.length bytes from a specified byte array to this file

13. Void Write (byte[] b, int off, int len)

Writes Len bytes from a specified byte array to this file and starts at offset off

14. void Write (int b)

Writes a specified byte to this file

15, void Writeboolean (Boolean v)

Writes a Boolean to the file by a single-byte value, and the remaining writebyte (int v), writebytes (String s), Writechar (int v), and so on, are similar

Randomaccessfile Use Instances

Define an entity class first:

 Public classemployee{PrivateString name; Private intAge ; Private Final Static intLEN = 8;  PublicEmployee () {} PublicEmployee (String name,intAge ) {        if(Name.length () >LEN) {Name= name.substring (0, 8); }        Else        {             while(Name.length () <LEN) {Name= name + "\u0000"; }        }         This. Name =name;  This. Age =Age ; }         PublicString GetName () {returnname; }         Public voidsetName (String name) { This. Name =name; }         Public intGetage () {returnAge ; }         Public voidSetage (intAge ) {         This. Age =Age ; }}

The first part, write the file, the file is not in the path, so Java will automatically help us create:

New Employee ("Zhangsan",new employee ("Lisi",new employee ("Wangwu");         New randomaccessfile ("D:/employee.txt", "RW"); Raf0.writebytes (E1.getname ()); Raf0.writeint ( E1.getage ()); Raf0.writebytes (E2.getname ()); Raf0.writeint (E2.getage ()); Raf0.writebytes (E3.getname ()); Raf0.writeint (E3.getage ()); Raf0.close ();

The file is created, and the file is on the D drive, so read on, here are some tips to demonstrate the Seek method and the Skipbytes method:

Randomaccessfile RAF1 =NewRandomaccessfile ("D:/employee.txt", "R");intLen = 8; Raf1.skipbytes (12);//Skip the first employee's information, whose name is 8 bytes, age 4 bytesSYSTEM.OUT.PRINTLN ("Information for the second employee:"); String Str= ""; for(inti = 0; i < Len; i++) {str= str + (Char) Raf1.readbyte ();} System.out.println ("Name:" +str); System.out.println ("Age:" +raf1.readint ()); System.out.println ("Information for the first employee:"); Raf1.seek (0); Str= ""; for(inti = 0; i < Len; i++) {str= str + (Char) Raf1.readbyte ();} System.out.println ("Name:" +str); System.out.println ("Age:" +raf1.readint ()); System.out.println ("Information for the third employee:"); Raf1.skipbytes (12);//Skip the second employee's informationstr = ""; for(inti = 0; i < Len; i++) {str= str + (Char) Raf1.readbyte ();} System.out.println ("Name:" +Str.trim ()); System.out.println ("Age:" +raf1.readint ()); Raf1.close ();

Look at the results of the operation:

information for the second employee: name:lisiage: First Employee information: name:zhangsanage: Third employee information: name:wangwuage:25

It may be strange that "Zhangsan" plus an int skips 12 bytes to understand, but "Lisi", "Wangwu" why add int to skip 12 bytes? Obviously "Lisi" only 4 bytes, "Wangwu" only 6 bytes ah. This involves a "byte alignment" problem, interested to understand. In addition, say again, randomaccessfile use finished must be in time close ().

Java Io2:randomaccessfile

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.