Java randomaccessfile Usage

Source: Internet
Author: User
Tags file copy first string readable

Randomaccessfile

Randomaccessfile is used to access files that hold data records, you can use the Seek () method to access the records and read and write them. The sizes of these records do not have to be the same, but their size and position must be knowable. However, this class is limited to manipulating files.
Randomaccessfile does not belong to the InputStream and OutputStream class systems. In fact, in addition to implementing the Datainput and DataOutput interfaces (both DataInputStream and DataOutputStream implement both interfaces), it has nothing to do with these two classes, Do not even use any of the features that already exist in the InputStream and OutputStream classes; it is a completely independent class, and all methods (most of them belong to itself) are written from scratch. This may be because randomaccessfile can move back and forth within a file, so its behavior is fundamentally different from other I/O classes. In summary, it is a separate class that inherits directly from object.
Basically, the way Randomaccessfile works is to combine DataInputStream and dataoutputstream, plus some of its own methods, such as the getfilepointer of positioning (), The Seek () to be moved in the file, and the number of bytes to determine the length (), skipbytes () of the file size skipped. In addition, its constructor has a parameter that indicates whether to open the file as read-only ("R") or read-write ("RW") (fopen () of C). It does not support write-only files.
Only Randomaccessfile has a seek search method, and this method applies only to files. Bufferedinputstream has a mark () method that you can use to set the tag (save the result in an internal variable), and then call Reset () to return to that position, but it is too weak and not practical.
The vast majority of randomaccessfile features, but not all, have been superseded by the "memory-mapped files" of the JDK 1.4 NiO (memory-mapped files), and you should consider whether to use "memory-mapped files" To replace the randomaccessfile.

Importjava.io.IOException;ImportJava.io.RandomAccessFile; Public classTestrandomaccessfile { Public Static voidMain (string[] args)throwsIOException {randomaccessfile RF=NewRandomaccessfile ("Rtest.dat", "RW");  for(inti = 0; I < 10; i++) {            //write basic type Double dataRf.writedouble (i * 1.414);        } rf.close (); RF=NewRandomaccessfile ("Rtest.dat", "RW"); //move the file pointer directly behind the 5th double dataRf.seek (5 * 8); //overwrite 6th double dataRf.writedouble (47.0001);        Rf.close (); RF=NewRandomaccessfile ("Rtest.dat", "R");  for(inti = 0; I < 10; i++) {System.out.println ("Value" + i + ":" +rf.readdouble ());    } rf.close (); }}&nbsp;
Memory-Mapped files

Memory-mapped files allow you to create and modify files that are too large to fit into memory. With a memory-mapped file, you can assume that the file has all been read into memory, and then it is accessed as a very large array. This solution greatly simplifies the code to modify the file.
Filechannel.map (Filechannel.mapmode mode, long position, long size) maps the file area of this channel directly into memory. Note that you have to indicate where it starts mapping from where the file is, how big the map is, and that is, it can also map a small fragment of a large file.

Mappedbytebuffer is a subclass of Bytebuffer, so it has all the methods of Bytebuffer, but new force () forces the contents of the buffer to be flushed to the storage device, load () loads the data from the storage device into memory, IsLoaded () The data in memory is synchronized with the storage settings. In addition to the put () and get () methods, you can easily read and write basic type data by using methods such as Ascharbuffer () to get a buffered view of the corresponding basic type of data.

ImportJava.io.RandomAccessFile;ImportJava.nio.MappedByteBuffer;ImportJava.nio.channels.FileChannel; Public classLargemappedfiles {Static intlength = 0x8000000;//Mb     Public Static voidMain (string[] args)throwsException {//to open the file in a readable and writable manner, use Randomaccessfile to create the file. FileChannel FC =NewRandomaccessfile ("Test.dat", "RW"). Getchannel (); //Note that the readable writable file channel is based on the file stream itself can be read and writtenMappedbytebuffer out = Fc.map (FileChannel.MapMode.READ_WRITE, 0, length); //Write 128M content         for(inti = 0; i < length; i++) {Out.put (byte) ' X '); } System.out.println ("Finished writing"); //read the middle of the file 6 bytes of content         for(inti = LENGTH/2; I < LENGTH/2 + 6; i++) {System.out.print (Char) Out.get (i));    } fc.close (); }}

Although map writes seem to use FileOutputStream, all output from the mapping file must use Randomaccessfile, but if you only need to read FileInputStream, you can use the Be sure to use random access files when writing a map file, and why you might want to read it when writing.

The program creates a 128Mb file that can cause memory overflow if read to memory at once, but the access here seems like just a flash, because the only small part of the memory is actually transferred, and the rest is placed on the swap file. This makes it easy for you to modify very large files (up to 2 GB). Note that Java is called the "file mapping mechanism" of the operating system to improve performance.

Applications of the Randomaccessfile class:

/** Program function: Demonstrates the operation of the Randomaccessfile class, and implements a file copy operation. */ PackageCom.lwj.demo;ImportJava.io.*; Public classRandomaccessfiledemo { Public Static voidMain (string[] args)throwsException {randomaccessfile file=NewRandomaccessfile ("File", "RW"); //The following writes data to file filesFile.writeint (20);//accounted for 4 bytesFile.writedouble (8.236598);//accounted for 8 bytesFile.writeutf ("This is a UTF string");//This length is written at the first two bytes of the current file pointer and can be read by Readshort ()File.writeboolean (true);//accounted for 1 bytesFile.writeshort (395);//accounted for 2 bytesFile.writelong (2325451l);//accounted for 8 bytesFile.writeutf ("Again a UTF string"); File.writefloat (35.5f);//accounted for 4 bytesFile.writechar (' a ');//accounted for 2 bytesFile.seek (0);//set the file pointer position to the beginning of the file//The following reads the data from the file file, paying attention to the location of the document PointerSYSTEM.OUT.PRINTLN ("—————— read data from the file file specified location ——————");  System.out.println (File.readint ());  System.out.println (File.readdouble ());  System.out.println (File.readutf ()); File.skipbytes (3);//skips the file pointer by 3 bytes, which in this case skips a Boolean and short values. System.out.println (File.readlong ()); File.skipbytes (File.readshort ()); //skipping the bytes of "another UTF string" in the file, note that the Readshort () method moves the file pointer, so you don't have to add 2. System.out.println (File.readfloat ()); //The following demo file copy OperationSystem.out.println ("—————— File replication (from file to FileCopy) ——————"); File.seek (0); Randomaccessfile fileCopy=NewRandomaccessfile ("FileCopy", "RW"); intLen= (int) File.length ();//get file Length (in bytes)  byte[] b=New byte[Len];  File.readfully (b);  Filecopy.write (b); System.out.println ("Copy done!" "); }}
Randomaccessfile Insert Write Example:
/** *  * @paramSkip Skips how many bytes to insert data *@paramstr to insert the string *@paramFileName File path*/ Public Static voidBeiju (LongSkip, String str, string fileName) {    Try{Randomaccessfile RAF=NewRandomaccessfile (FileName, "RW"); if(Skip < 0 | | Skip >raf.length ()) {System.out.println ("Skip byte count is invalid"); return; }        byte[] B =str.getbytes (); Raf.setlength (Raf.length ()+b.length);  for(Longi = Raf.length ()-1; I > b.length + skip-1; i--) {Raf.seek (i-b.length); bytetemp =Raf.readbyte ();            Raf.seek (i);        Raf.writebyte (temp);        } raf.seek (skip);        Raf.write (b);    Raf.close (); } Catch(Exception e) {e.printstacktrace (); }}
Using Randomaccessfile to implement multi-threaded download of files, that is, multi-threaded download a file, the file is divided into several pieces, each with a different thread to download. Here is an example of using multithreading when writing a file, where pre-allocating the space required for a file, then chunking in the allocated space, and then writing:
Importjava.io.FileNotFoundException;Importjava.io.IOException;ImportJava.io.RandomAccessFile;/*** Test using multi-threading for file write operations*/ Public classTest { Public Static voidMain (string[] args)throwsException {//The disk space that the pre-allocated file occupies, and a file of the specified size is created on the diskRandomaccessfile RAF =NewRandomaccessfile ("D://abc.txt", "RW"); Raf.setlength (1024*1024);//pre-allocating 1M of file spaceRaf.close (); //The contents of the file to be writtenstring S1 = "First string"; String S2= "Second string"; String S3= "Third string"; String S4= "Fourth string"; String S5= "Fifth string"; //write a file at the same time using multithreading        NewFilewritethread (1024*1,s1.getbytes ()). Start ();//start writing data from 1024 bytes of file        NewFilewritethread (1024*2,s2.getbytes ()). Start ();//start writing data from 2048 bytes of file        NewFilewritethread (1024*3,s3.getbytes ()). Start ();//start writing data from 3072 bytes of file        NewFilewritethread (1024*4,s4.getbytes ()). Start ();//start writing data from 4096 bytes of file        NewFilewritethread (1024*5,s5.getbytes ()). Start ();//start writing data from 5120 bytes of file    }        //use threads to write specified data at a specified location in a file    Static classFilewritethreadextendsthread{Private intSkip; Private byte[] content;  PublicFilewritethread (intSkipbyte[] content) {             This. Skip =Skip;  This. Content =content; }                 Public voidrun () {Randomaccessfile RAF=NULL; Try{RAF=NewRandomaccessfile ("D://abc.txt", "RW");                Raf.seek (skip);            Raf.write (content); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally {                Try{raf.close (); } Catch(Exception e) {}}} }}

Java randomaccessfile Usage

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.