Java programming note 16 Random Access File class randomaccessfile

Source: Internet
Author: User

The random access to a file is mainly completed through randomaccessfile. It uses the seek () method to move a record from the file to the next record for reading or writing, without knowing the total number of records. It does not need to load all the records into the memory for read/write. This is an efficient choice for accessing large files.

Constructor: two methods to determine the corresponding file: String path and file

Constructor Summary
RandomAccessFile(File file, String mode)
Creates a random access file stream from which to read and write (optional) to it.FileParameter.
RandomAccessFile(String name, String mode)
Creates a random access file stream to read from and write to (Optional). The file has the specified name.

Common Methods:

Method Summary
 void close()
Disable the random access to the file stream and release all system resources associated with the stream.
 FileChannel getChannel()
Returns the unique ID associated with the file.FileChannelObject.
 FileDescriptor getFD()
Returns the opaque file descriptor object associated with the stream.
 long getFilePointer()
Returns the current offset in this file.
 long length()
Returns the length of the file.
 int read()
Read a Data byte from this file.
 int read(byte[] b)
Maximumb.lengthData bytes are read into the byte array from this file.
 int read(byte[] b, int off, int len)
MaximumlenData bytes are read into the byte array from this file.
 boolean readBoolean()
Read one from this fileboolean.
 byte readByte()
Read a signed eight-bit value from this file.
 char readChar()
Read one character from this file.
 double readDouble()
Read one from this filedouble.
 float readFloat()
Read one from this filefloat.
 void readFully(byte[] b)
Setb.lengthBytes are read from this file into the byte array and start from the current file pointer.
 void readFully(byte[] b, int off, int len)
Will be exactlylenBytes are read from this file into the byte array and start from the current file pointer.
 int readInt()
Read a signed 32-bit integer from this file.
 String readLine()
Read the next line of text from this file.
 long readLong()
Read a signed 64-bit integer from this file.
 short readShort()
Read a signed 16-digit number from this file.
 int readUnsignedByte()
Read an unsigned eight-digit number from this file.
 int readUnsignedShort()
Read an unsigned 16-digit number from this file.
 String readUTF()
Read a string from this file.
 void seek(long pos)
Sets the file pointer offset measured at the beginning of the file. The next read or write operation occurs at this position.
 void setLength(long newLength)
Set the length of the file.
 int skipBytes(int n)
Try to skip the inputnBytes to discard the skipped bytes.
 void write(byte[] b)
Setb.lengthBytes are written to this file from the specified byte array and start from the current file pointer.
 void write(byte[] b, int off, int len)
SetlenBytes written from the specified byte array to this file, and from the offsetoff.
 void write(int b)
Write the specified byte to this file.
 void writeBoolean(boolean v)
ConvertbooleanWrite this file.
 void writeByte(int v)
ConvertbyteWrite this file.
 void writeBytes(String s)
Write the string to the file in byte sequence.
 void writeChar(int v)
ConvertcharWrite this file, first write the high byte.
 void writeChars(String s)
Write a string to the file in a string sequence.
 void writeDouble(double v)
UseDoubleClassdoubleToLongBitsMethod to convert a double-precision parameter tolongAnd then addlongValue to write to the file, first set the height of the byte.
 void writeFloat(float v)
UseFloatClassfloatToIntBitsMethod to convert a floating point parameter tointAnd thenintValue to write to the file, first write to the high byte.
 void writeInt(int v)
In four bytesintWrite this file, first write the high byte.
 void writeLong(long v)
ConvertlongWrite this file, first write the high byte.
 void writeShort(int v)
In two bytesshortWrite this file, first write the high byte.
 void writeUTF(String str)
Write a string to the file in a machine-independent manner using the modified UTF-8 encoding.

Test Program: four pieces of person data are written to the file according to a certain format (each field is written to the file), then the entire file is randomly traversed, and all records are output. Then, find the record containing the keyword.

Package fileoperation; import Java. io. ioexception; import Java. io. randomaccessfile; import Java. util. arraylist; import Java. util. list; public class filerandomaccess {/** name length in the file */public static final int name_length = 100; /** length of the age file */public static final int int_length = 8; public static final int description_length = 200; /** length of each person record in the file */public static final int person_length = name_length + Int_length + description_length; // internal class static class person {public string name; Public int age; Public String description; Public Person (string name, int age, string description) {This. name = Name; this. age = age; this. description = description;} Public String tostring () {return "person [name = \" "+ name +" \ ", age = \" "+ age + "\", description = \ "" + description + "\"] ";}// defines an array of the person Type Static person [] Person = new person [] {new person ("Du Fu", 45, "Tang Dynasty realism poet"), new person ("Einstein", 20, "great physicist, propose the theory of relativity. "), New person (" Li Bai ", 20," Tang Dynasty romantic poet "), new person (" Cao Xueqin ", 47," author of Dream of Red Mansions "),}; // main function public static void main (string [] ARGs) throws ioexception {// construct a file object randomaccessfile = new randomaccessfile ("C: \ person. dat "," RW "); // set the file length based on the initialization data. setlength (person. length * person_length); For (INT I = 0; I <person. length; I ++) {writeperson (file, person [I]); // call writeperson} system. out. println ("\ r \ n lists all the data in the file:"); person [] allpersons = listallperson (File ); // call listallperson to return a person array for (INT I = 0; I <allpersons. length; I ++) {system. out. println (allpersons [I]);} system. out. println ("\ r \ n in the file to find the keyword snow, the result is as follows:"); person P = findperson (file, "snow "); // call findperson to find the keywordsystem in the file. out. println ("Result:" + p); file. close () ;}// write string data. Note the difference between writing string and writing Int. Public static void writestring (randomaccessfile file, string name, int fieldlength) throws ioexception {file. writeutf (name); int length = Name. getbytes ("UTF-8 "). length; file. skipbytes (fieldlength-length); // skip unused bytes and keep alignment} // write int type data public static void writeint (randomaccessfile file, int age) throws ioexception {file. writeint (AGE);} // write person object (write string, write INT) public static void writeperson (randomaccessfile file, person) throws ioexception {writestring (file, person. name, name_length); writeint (file, person. age); writestring (file, person. description, description_length);} // read string-type data public static string readstring (randomaccessfile file, int fieldlength) throws ioexception {string name = file. readutf (); int length = Name. getbytes ("UTF-8 "). length; file. skipbytes (fieldlength-length); Return name;} // read int type data public static int readint (randomaccessfile file) throws ioexception {return file. readint ();} // read the person object (read string, read INT) public static person readperson (randomaccessfile file) throws ioexception {// find the file header if (file. getfilepointer ()> = file. length () {return NULL;} return new person (readstring (file, name_length), // namereadint (file), // agereadstring (file, description_length) // description);} // list all data in the data file public static person [] listallperson (randomaccessfile file) throws ioexception {list = new arraylist (); file. seek (0); While (true) {person = readperson (File); If (person = NULL) break; List. add (person);} person [] person = new person [list. size ()]; List. toarray (person); Return person;} // find the Qualified Data public static person findperson (randomaccessfile file, string keyword) throws ioexception {// query the record file from the beginning. seek (0); While (true) {person = readperson (File); // read a person each time. Note that if (person = NULL) must be moved backwards for each seek) break; If (person. name. contains (keyword) {return person ;}} return NULL ;}}

Running result:


List all data in the file:
Person [name = "Du Fu", age = "45", description = "Tang Dynasty realism poet"]
Person [name = "Einstein", age = "20", description = "great physicist, proposing the theory of relativity. "]
Person [name = "Li Bai", age = "20", description = "Tang Dynasty romantic poet"]
Person [name = "Cao Xueqin", age = "47", description = "author of Dream of Red Mansions"]

Search for the keyword snow in the file. The result is as follows:
Result: person [name = "Cao Xueqin", age = "47", description = "author of Dream of Red Mansions"]

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.