Java Randomaccessfile Usage Detailed _java

Source: Internet
Author: User

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. These records do not have to be the same size, but their size and location must be knowable. However, the class is limited to operation files.

Randomaccessfile does not belong to the InputStream and OutputStream classes. In fact, in addition to implementing the Datainput and DataOutput interfaces (DataInputStream and DataOutputStream also implement these two interfaces), it has nothing to do with the two-class systems, You don't even use any of the features that already exist in the InputStream and OutputStream classes; it's a completely separate class, and all the methods (most of which belong to themselves) are written from scratch. This may be because randomaccessfile can move around in a file, so its behavior is fundamentally different from other I/O classes. In short, it is a standalone class that inherits object directly.

Basically, the way Randomaccessfile works is to combine DataInputStream with DataOutputStream, plus some of its own methods, such as the getfilepointer of positioning (), The Seek () that is moved in the file, and the length (), skipbytes () of the file size is determined and the number of bytes skipped. In addition, its constructor also has an argument for opening the file in read-only ("R") or read-write ("RW") (identical to the fopen () of C). It does not support write-only files.

Only Randomaccessfile has a 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 its functionality is too weak and not practical.

Most of the functionality of Randomaccessfile, but not all, has been replaced 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.

Import java.io.IOException; 
Import Java.io.RandomAccessFile; 
 
public class Testrandomaccessfile {public 
  static void Main (string[] args) throws IOException { 
    Randomaccessfile RF = new Randomaccessfile ("Rtest.dat", "RW"); 
    for (int i = 0; i < i++) { 
      //write base type Double data 
      rf.writedouble (i * 1.414); 
    } 
    Rf.close (); 
    RF = new Randomaccessfile ("Rtest.dat", "RW"); 
    Move the file pointer directly behind the 5th double data 
    Rf.seek (5 * 8); 
    Overlay 6th Double Data 
    rf.writedouble (47.0001); 
    Rf.close (); 
    RF = new Randomaccessfile ("Rtest.dat", "R"); 
    for (int i = 0; i < i++) { 
      System.out.println ("Value" + i + ":" + rf.readdouble ()); 
    } 
    Rf.close (); 
  } 
  

Memory-Mapped files

Memory-mapped files allow you to create and modify files that are too large to be put into memory. With a memory-mapped file, you can assume that the file is fully read in memory and then accessed as a very large array. This workaround can greatly simplify the code that modifies the file.

Filechannel.map (Filechannel.mapmode mode, long position, long size) maps the file area of this channel directly into memory. Note that you must indicate where the file is mapped from and how wide the map is, that is, it can also map a small fragment of a large file.

Mappedbytebuffer is a subclass of Bytebuffer, so it has all the bytebuffer methods, but the 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, Whether the data in the isLoaded () location is synchronized with the storage settings. This is a simple demonstration of the put () and get () methods, and you can use the Ascharbuffer () method to obtain a buffer view of the corresponding base type data, and then read and write the basic type data conveniently.

Import Java.io.RandomAccessFile; 
Import Java.nio.MappedByteBuffer; 
Import Java.nio.channels.FileChannel; 
 
public class Largemappedfiles { 
  static int length = 0x8000000//128 Mb public 
 
  static void Main (string[] args) th Rows Exception { 
    //To open the file in a readable and writable manner, use Randomaccessfile to create the file. 
    FileChannel fc = new Randomaccessfile ("Test.dat", "RW"). Getchannel (); 
    Note that the readable writeable of the file channel is based on the 
    mappedbytebuffer out = Fc.map (FileChannel.MapMode.READ_WRITE, 0, length) on the basis that the file stream itself is readable and writable; 
    Write 128M content for 
    (int i = 0; i < length; i++) { 
      out.put ((Byte) ' x '); 
    } 
    System.out.println ("finished writing"); 
    Reads 6 bytes in the middle of the file for 
    (int i = LENGTH/2 I < LENGTH/2 + 6; i++) { 
      System.out.print ((char) out.get (i)); 
    } 
    Fc.close (); 
  } 
 

Although mapping writes seem to use FileOutputStream, all output in the mapping file must use Randomaccessfile, but if you only need to read to use FileInputStream, be sure to use random access files when writing the mapping file. Maybe it's a reason to read when you write.

This program creates a 128Mb file, and if read memory at a time can cause a memory overflow, the access here seems to be just for a moment, because the real memory is only a small part of it, the rest is placed on the swap file. This allows you to easily modify the oversize files (up to 2 GB). Note that Java is called the operating system's "file mapping mechanism" to improve performance.

Application of Randomaccessfile class:

* * Program function: Demonstrated the operation of the Randomaccessfile class, while implementing a file copy operation. 
 
* * Package Com.lwj.demo; 
 
Import java.io.*; public class Randomaccessfiledemo {public static void main (string[] args) throws Exception {Randomaccessfile file = 
 New Randomaccessfile ("File", "RW"); The following writes data to the file File.writeint (20),//occupies 4 bytes file.writedouble (8.236598),//occupies 8 bytes File.writeutf ("This is a UTF string");//This length is written At the first two bytes of the current file pointer, you can read File.writeboolean (true) with Readshort () and/or 1 bytes file.writeshort (395);//2 bytes File.writelong (232545 
 1l);//Account for 8 bytes File.writeutf ("Again a UTF string"); File.writefloat (35.5f);//4 bytes File.writechar (' a ');//2 bytes file.seek (0);//Set file pointer position to file at start//below read data from file, note 
 The position of the document Pointer System.out.println ("—————— read data from the file specified ——————"); 
 System.out.println (File.readint ()); 
 System.out.println (File.readdouble ()); 
 
 System.out.println (File.readutf ()); 
 File.skipbytes (3)//Skips the file pointer over 3 bytes, in this case skipping a Boolean and a short value. 
 
 System.out.println (File.readlong ()); File.skipbytes (File.readshort ()); Skipping files"Again a UTF string" in bytes, note that the Readshort () method moves the file pointer, so do not add 2. 
  
 System.out.println (File.readfloat ()); 
 The following demo file copy Operation System.out.println ("—————— file to FileCopy) ——————"); 
 File.seek (0); 
 Randomaccessfile filecopy=new randomaccessfile ("FileCopy", "RW"); 
 int len= (int) file.length ()//Get file Length (bytes) byte[] B=new Byte[len]; 
 File.readfully (b); 
 Filecopy.write (b); System.out.println ("Copy complete!") 
 ");  } 
}

Randomaccessfile Insert Write Example:

/** 
 * * 
 @param skip skips how many bytes to insert data 
 * @param str the string to insert 
 * @param fileName file path/public 
static VO ID beiju (long skip, String str, string fileName) { 
  try { 
    Randomaccessfile RAF = new Randomaccessfile (fileName, rw) ); 
    if (Skip < 0 | | | | skip > Raf.length ()) { 
      System.out.println ("Skipped byte number invalid"); 
      return; 
    } 
    Byte[] B = str.getbytes (); 
    Raf.setlength (Raf.length () + b.length); 
    for (Long i = Raf.length ()-1; i > b.length + skip-1; i--) { 
      raf.seek (i-b.length); 
      byte temp = Raf.readbyte (); 
      Raf.seek (i); 
      Raf.writebyte (temp); 
    } 
    Raf.seek (skip); 
    Raf.write (b); 
    Raf.close (); 
  } catch (Exception e) { 
    e.printstacktrace (); 
  } 
} 

The use of randomaccessfile to achieve a multithreaded download of files, that is, multithreading to download a file, the file into several pieces, each with a different thread to download. Here is an example of using multithreading to write a file, which allocates the space required for a file, blocks it in the allocated space, and writes:

Import java.io.FileNotFoundException; 
Import java.io.IOException; 
 
Import Java.io.RandomAccessFile; /** * Test use multithreading for file writes/public class Test {public static void main (string[] args) throws Exception {//Pre 
    Allocate the disk space of the file, create a file of the specified size on the disk randomaccessfile RAF = new Randomaccessfile ("D://abc.txt", "RW"); Raf.setlength (1024*1024); 
     
    Pre-allocated 1M file space Raf.close (); 
    The contents of the file to be written string S1 = "First string"; 
    String s2 = "Second string"; 
    String s3 = "Third string"; 
    String S4 = "Fourth string"; 
     
    String S5 = "Fifth string"; Use multithreading to write a file New Filewritethread (1024*1,s1.getbytes ()) at the same time. Start (); Writes data new Filewritethread (1024*2,s2.getbytes ()) after 1024 bytes of the file. Start (); Writes data new Filewritethread (1024*3,s3.getbytes ()) after 2048 bytes of the file. Start (); Writes data new Filewritethread (1024*4,s4.getbytes ()) after 3072 bytes of the file. Start (); Writes data new Filewritethread (1024*5,s5.getbytes ()) after 4096 bytes of the file. Start (); Write data from 5120 bytes of file}///Use thread to write specified number at specified location in fileAccording to Static class Filewritethread extends thread{private int skip; 
     
    Private byte[] content; 
      Public filewritethread (int skip,byte[] content) {This.skip = skip; 
    this.content = content; 
      public void Run () {Randomaccessfile RAF = null; 
        try {RAF = new Randomaccessfile ("D://abc.txt", "RW"); 
        Raf.seek (skip); 
      Raf.write (content); 
      catch (FileNotFoundException e) {e.printstacktrace (); 
      catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
        Finally {try {raf.close ();  The catch (Exception e) {}}}}

Above this Java randomaccessfile usage is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.