Java_io System Randomaccessfile Introduction, into the source code and example--20

Source: Internet
Author: User

Java_io System Randomaccessfile Introduction, into the source code and example--20

RandomAccessFile1, class features Introduction:

File random access stream, care several features:

1, he realized the interface is no longer inputstream, outputstream any one, but the realization of datainput, dataoutput. It was also destined that he could manipulate the Java base type, read it, write it, and most of the methods on this part were swung from DataInputStream and DataOutputStream.

2, such as its name, random flow, where the random is not uncontrollable, unpredictable to access the file, but can be positioned through the form of pointers to the specific location-"file pointer", the specific use of "file pointer" method: Call this stream's seek (long N) method to set the location, The use of this method is to note that if the incoming n is greater than the file length, this method does not change the file length, but only when the next byte is written, the file size is changed, i.e. the next write byte is added after N. If n is less than the file length, the following file content is overwritten from the n position,

3, this stream can read the file, can also write to the file, can also have read-only function, but there is no write-only function, specifically which type is specified in the construction method of the--string mode, the specific difference is described above:

Here The example is put in front, because the source code and methods occupy too long, interested can continue to look down.

2, example demonstration:

Package Com.chy.io.original.test;import Java.io.file;import Java.io.ioexception;import java.io.RandomAccessFile; public class Randomaccessfiletests {private static final file File = new file ("D:\\rsf.txt");/** * Write content to file */public Stati c void Testrandomaccessfilewriter () throws ioexception{//to first delete the existing files and avoid interference. if (file.exists ()) {File.delete ();} Randomaccessfile rsfwriter = new Randomaccessfile (file, "RW");//does not change the file size, but he will identify the write position of the next character as 10000, that is, as soon as the content is written, That is, starting from 10001, Rsfwriter.seek (10000);p rintfilelength (rsfwriter),//result:0//will change the file size, just change the file's size, Does not change the location of the next content to be written, commented out here to verify the description of the Seek method above//rsfwriter.setlength (10000);p rintfilelength (rsfwriter);//result:0// Each man occupies 3 bytes and writes a string with a record of two bytes written to the length of the string Rsfwriter.writeutf ("Chen Hua");p rintfilelength (rsfwriter);//result:10011// Each character occupies two bytes Rsfwriter.writechar (' a '), Rsfwriter.writechars ("ABCDE");p rintfilelength (rsfwriter);//result:10023//again from " The file pointer "for 5000 places a length of 100, the content is all ' a ' character array//The file length here is still 10023, because he is from the" file pointer "for 5000 of the place covered by the next 200 bytes, subscript and not more than the length of Rsfwriter.seek ( Char[] Cbuf= new Char[100];for (int i=0; i 

3, Randomaccessfile API Introduction: A: Construction method
Randomaccessfile (file file, String mode)     creates a random-access file stream from which to read and write (optionally), which is specified by the file parameter. Randomaccessfile (string name, string mode)  
Add one: The value of mode has the following four kinds of conditions
"R" opens as read-only. Any write method that invokes the result object will cause the IOException to be thrown.
"RW" opens for read and write.
"RWS" opens for reading and writing. In contrast to "RW", "RWS" also requires that each update to the content of the file or metadata be written to the underlying storage device synchronously.
"RWD" is opened for reading and writing, and "RWD" requires that each update to the contents of the file be synchronously written to the underlying storage device, relative to "RW".
Supplementary two: "Meta-data" on documents
The definition of metadata is "data on other data." With a file system, the data is contained on its files and directories, and the metadata tracks information on each of These objects:is it a regular file, a directory, or a link? What is it size, creation date, last modified date, file owner, group owner, and access permissions?
Supplement three: The difference between "RW" "RWS" "RWD"
The "RWS" or "RWD", "RW" makes a difference when the file being manipulated is stored on the local underlying storage device (such as hard disk, Nandflash, etc.).
When the pattern is "RWS" and the files on the underlying storage device are being manipulated, the changes are synchronized to the underlying storage device each time "changes to file contents [such as write () writes data]" or "modifies file metadata (such as file Mtime)".
When the pattern is "RWD" and the files on the underlying storage device are being manipulated, the changes are synchronized to the underlying storage device each time "changes to file contents [such as write () writes data]".
When the mode is "RW" and the file is operating on the underlying storage device, then "Modify file Content" is synchronized to the underlying storage device when the file is closed. As for, whether the "Change file contents" is synchronized immediately depends on the system's underlying implementation.
General use the first two is OK.
B: General method
 void Close () closes this random access file stream and frees all system resources associated with the stream. FileChannel Getchannel () returns the unique FileChannel object associated with this file. FileDescriptor GETFD () returns the opaque file descriptor object associated with this stream. Long Getfilepointer () returns the current offset in this file. Long Length () returns the length of this file. int read () reads a byte of data from this file. int read (byte[] b) reads a maximum of b.length data bytes from this file into a byte array. int read (byte[] b, int off, int len) will read up to Len data bytes from this file into a byte array. Boolean Readboolean () reads a Boolean from this file. BYTE readbyte () reads a signed eight-bit value from this file. Char ReadChar () reads a character from this file. Double readdouble () reads a double from this file. Float readfloat () reads a float from this file. void Readfully (byte[] b) reads B.length bytes from this file into a byte array and starts with the current file pointer. void Readfully (byte[] b, int off, int len) will read exactly Len bytes from this file into a byte array and start with the current file pointer. int readInt () reads a signed 32-bit integer from this file. String ReadLine () reads the next line of text from this file. Long Readlong () reads a signed 64-bit integer from this file. Short Readshort () reads a signed 16-digit number from this file. int Readunsignedbyte () reads an unsigned eight-digit number from this file. int Readunsignedshort () reads an unsigned 16-digit number from this file. String readUTF () from thisThe file reads a string. void Seek (Long POS) sets the offset of the file pointer to the beginning of this file, where the next read or write operation occurs. void SetLength (Long newlength) sets the length of this file. int skipbytes (int n) attempts to skip the input n bytes to discard the skipped bytes. void Write (byte[] b) writes B.length bytes from a specified byte array to this file, starting with the current file pointer. void Write (byte[] b, int off, int len) writes Len bytes from a specified byte array to this file and starts at offset off. void write (int b) writes the specified bytes to this file. void Writeboolean (Boolean V) writes a Boolean to the file by a single-byte value. void WriteByte (int v) writes a byte to the file by a single-byte value. void Writebytes (string s) writes the string to the file in a sequence of bytes. void Writechar (int v) writes a char to the file by a double-byte value, writing the high byte first. void WriteChars (string s) writes a string to the file by a sequence of characters. void writedouble (double v) uses the Doubletolongbits method in the double class to convert the double parameter to a long, and then writes the long value to the file by eight bytes, first setting the high byte. void Writefloat (float v) uses the Floattointbits method in the float class to convert a floating-point parameter to an int, and then writes the int value to the file in four-byte quantities, with the high byte first. void Writeint (int v) writes an int to the file in four bytes, writing the high byte first. void Writelong (Long v) writes a long to the file in eight bytes, writing the high byte first. void Writeshort (int v) writes a short to the file in two bytes and writes the high byte first.    void writeUTF (String str) Use modified UTF-8 encoding to write a string to the file in a machine-independent manner.  
4. Source Code Analysis

Package Com.chy.io.original.code;import Java.io.closeable;import Java.io.eofexception;import java.io.File;import Java.io.filedescriptor;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.io.utfdataformatexception;import Java.nio.channels.filechannel;import sun.nio.ch.filechannelimpl;/** * Random access to the file stream, can read from the file, can also write to the file, can also be written to the Java base type, no longer inputstream or outputstream subclass, * But implemented DataOutput, Datainput, As can be seen from both interfaces, this class has the ability to write to or read from a Java base type to a program, and most of the operations on the write/read file base type * are plagiarism datainputstream/dataoutputstream. */public class Randomaccessfile implements DataOutput, Datainput, closeable {java.io.RandomAccessFile private FILEDESCR    Iptor FD;    Private FileChannel channel = null;    The private Boolean rw;//identifies whether this file can be read and write//identify different mode values for the private static final int o_rdonly = 1;    private static final int o_rdwr = 2;    private static final int o_sync = 4;    private static final int o_dsync = 8; /** * Use specified file, pattern construct randomaccessfile, initialize parameter, open connection to file */public RandomAccessfile (string name, String mode) throws FileNotFoundException {This (name! = null? New File (name): null, MO    DE);  /** * uses the specified file, schema construction Randomaccessfile, initialization parameters, open to File connection */public randomaccessfile (file file, String mode) throws FileNotFoundException {String name = (file! = null? File.getpath (): null); int imode = -1;if (Mode.equals ("R")) im    Ode = O_rdonly;else if (Mode.startswith ("RW")) {imode = O_rdwr;    RW = true; if (Mode.length () > 2) {if (Mode.equals ("RWS")) Imode |= O_sync;else if (mode.equals ("RWD")) Imode |= o_dsync;els    E imode =-1; }}if (Imode len) {newpos = Len;}    Seek (Newpos);/* Return the actual number of bytes skipped */return (int) (NEWPOS-POS);     }//' Write ' primitives/** * Write a byte at the current "file pointer" */public native void write (int b) throws IOException;    /** * Writes part of B to the file */private native void Writebytes (byte b[], int off, int len) throws IOException;    /** * writes b to the file */public void Write (byte b[]) throws IOException {writebytes (b, 0, b.length); }/** * Writes part of B to the file */public void Write (byte b[], int off, int len) throws IOException {writebytes (b,    Off, Len); }//' Random access ' stuff/** * Returns the offset of the current file, which is the location of the "file descriptor" */public native long Getfilepointer () throws IOE    Xception;     /** * Sets the offset of the file pointer, counting from the beginning of the file, if the POS is larger than the length of the file, does not change the size of the file, the size of the file is only extended if the file pointer points to the end of the file and then to the file.    */public native void Seek (long pos) throws IOException;    /** * Returns the number of bytes of the file */public native long length () throws IOException;     /** * Set File Length: * if (Newlength > Originallength) * Extended file length, new added length with default value padding;     * Else * intercepts the original originallength bytes of the source file, if the source file has an offset greater than newlength, the source file offset is set to newlength;    */public native void SetLength (long newlength) throws IOException; /** * Closes this stream, frees all resources related to this stream */public void Close () throws IOException {if (channel! = null) chan        Nel.close (); CloSE0 ();    }//Some of the methods are stolen from Datainputstream/dataoutputstream ... /** * Reads a boolean data */Public final Boolean Readboolean () throws ioexception {int ch = this.read (); if (Ch >    > 8) & 0xFF), write ((v >>> 0) & 0xFF),//written + = 2;  }/** * Writes a char to the file */public final void Writechar (int v) throws IOException {write ((v >>> 8) &    0xFF) Write ((v >>> 0) & 0xFF);//written + = 2; }/** * writes an int to the file */public final void Writeint (int v) throws IOException {write ((v >>>) & 0xFF) Write ((v >>>) & 0xFF), write ((v >>> 8) & 0xFF), write ((v >>> 0) & 0xFF);//    Written + = 4; }/** * Writes a long file */public final void Writelong (Long v) throws IOException {write (int) (v >>> 56 & 0xFF), write ((int) (v >>> a) & 0xFF), write ((int) (v >>> +) & 0xFF), write ((int) (v >&gt ;> & 0xFF); write ((int) (V >>>) & 0xFF), write ((int) (v >>> +) & 0xFF), write ((int) (v >>> 8) & 0xFF); write ((int)    (v >>> 0) & 0xFF);//written + = 8; }/** * Writes a long file */public final void writefloat (float v) throws IOException {Writeint (FLOAT.FLOATTOINTBI    TS (v));     }/** * Writes a double to the file.    */public final void writedouble (Double v) throws IOException {Writelong (double.doubletolongbits (v)); /** * Converts a string into a sequence of ordered bytes written to */public final void Writebytes (String s) throws IOException {int len = s.length ()    ; byte[] B = new Byte[len];s.getbytes (0, Len, b, 0); Writebytes (b, 0, Len); /** * Writes a string to the file in a sequence of sequential characters */public final void WriteChars (String s) throws IOException {int clen = S.length (); int blen = 2*clen;byte[] b = new byte[blen];char[] c = new Char[clen];s.getchars (0, Clen, c, 0); for (int i = 0, j = 0;    I >> 8); B[j++] = (byte) (C[i] >>> 0);}    Writebytes (b, 0, Blen); }/** * Call DATAOUTPUTstream writeUTF (String str, dataoutput out) writes a string to the file.    */public final void writeUTF (String str) throws IOException {Dataoutputstream.writeutf (str, this);    } private static native void Initids ();    Private native void Close0 () throws IOException;    static {Initids (); }}

More IO Content: Directory of JAVA_IO Systems

Java_io System Randomaccessfile Introduction, into the source code and example--20

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.