Study Note 33: IO Stream (iv)

Source: Internet
Author: User
Tags first string

Nothing is a kind of wealth, it allows the poor to change the fate of action.

the content of this lecture: 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.

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 basic 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 (5 * 8);          Overwrites the 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 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.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.

public class Largemappedfiles {      static int length = 0x8000000;//-Mb public        static void Main (string[] args) th Rows Exception {          //In order to open a file in a readable and writable manner, the randomaccessfile is used to create the file.          FileChannel fc = new Randomaccessfile ("Test.dat", "RW"). Getchannel ();          Note that the readable writable file channel is based on the file stream itself can be read and written on the basis of          mappedbytebuffer out = (FileChannel.MapMode.READ_WRITE, 0, length);          Write 128M content for          (int i = 0; i < length; i++) {              out.put ((Byte) ' x ');          }          System.out.println ("finished writing");          Read the middle of the file 6 bytes of content for          (int i = 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.

Ra Application of the Ndomaccessfile class:

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);//4 bytes file.writedouble (8.236598);//8 bytes File.writeutf ("This is a UTF string");//This The length is written at the first two bytes of the current file pointer, Readshort () can be read File.writeboolean (true), or 1 bytes file.writeshort (395);//2 bytes File.writelong (2    325451L);//accounted for 8 bytes File.writeutf ("Again a UTF string"); File.writefloat (35.5f);//accounted for 4 bytes file.writechar (' a ');//accounted for 2 bytes (0);//Set the position of the file pointer to the beginning of the file//below read data from file    , note the position of the file pointer System.out.println ("—————— read data from the 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 over 3 bytes, skipping a Boolean and short values in this example.      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 Operation System.out.println ("—————— file to FileCopy ——————"); (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 done!   ");  }  }

randomaccessfile Insert Write Example:

/**  *   * @param skip skips how many bytes to insert data  * @param str to insert the string  * @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 ("Invalid skipped bytes");              return;          }          Byte[] B = str.getbytes ();          Raf.setlength (Raf.length () + b.length);          for (Long i = Raf.length ()-1; i > b.length + skip-1; i--) {     (i-b.length);              byte temp = Raf.readbyte ();     (i);              Raf.writebyte (temp);          } (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:

/** * Test using multithreading for file writes */public class Test {public static void main (string[] args) throws Exception {          The disk space that the pre-allocated file occupies, a file of the specified size is created on the disk randomaccessfile RAF = new Randomaccessfile ("D://abc.txt", "RW"); Raf.setlength (1024*1024);                    Pre-allocating 1M of file space Raf.close ();          The file content to be written to is string S1 = "First string";          String s2 = "Second string";          String s3 = "Third string";          String S4 = "Fourth string";                    String S5 = "Fifth string"; Write a File New Filewritethread (1024*1,s1.getbytes ()) at the same time using multithreading. Start (); Writes data new Filewritethread (1024*2,s2.getbytes ()) after 1024 bytes from the file. Start (); Writes data new Filewritethread (1024*3,s3.getbytes ()) after 2048 bytes from the file. Start (); Writes data new Filewritethread (1024*4,s4.getbytes ()) after 3072 bytes from the file. Start (); Writes data new Filewritethread (1024*5,s5.getbytes ()) after 4096 bytes from the file. Start (); Write data starting from 5120 bytes of file}//using thread to write specified data at specified location in a file 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");         (skip);              Raf.write (content);              } catch (FileNotFoundException e) {e.printstacktrace ();              } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();                  } finally {try {raf.close (); } catch (Exception e) {}}}}}

Randomaccessfile has the ability to automatically update the file, if you place the pointer in the middle of the file, instead of inserting the content at the pointer position, the file size will not increase at this time, unless you place the pointer at the end of the file.
This is the reason why my address book is wrong, if I inserted in the middle of the content, there will be the original part of the missing case.
Class Test {public  static void Main (string[] args) throws ioexception{    randomaccessfile r = new Randomaccessfile ( "Heihei.txt", "RW");     R.writechar (' a ');    R.writechar (' B ');    R.writechar (' C ');    Shouldn't the contents of this file be ABC? (2); The pointer is set after a.    R.writechar (' d '); The file should become adbc, but it seems not so, the following     stringbuffer strbuf = new StringBuffer (); (0); The pointer is returned to the initial position    Strbuf.append (R.readchar ());     Strbuf.append (R.readchar ());    Strbuf.append (R.readchar ());     Strbuf.append (R.readchar ());     System.out.println (STRBUF); The result is ADC  }}

This is where we go, take your time and enjoy it

Study Note 33: IO Stream (iv)

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: 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.