Random Read-Write class
The only parent class for Randomaccessfile is object, which is different from other stream parent classes. is used to access files that hold data records, so 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.
Randomaccessfile are not part of the InputStream and OutputStream classes. 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, Not even the InputStream and OutputStream have been prepared to function; 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.
Working mode:
Basically, the way randomaccessfile works is to glue DataInputStream and dataoutputstream together, plus some of its own methods, such as positioning getfilepointer (), The Seek () to be moved in the file, and the length () of the file size to be judged. 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, from this point of view, if Randomaccessfile inherit the DataInputStream, it may do better. Only Randomaccessfile has a seek 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, if not all, have been JDK1.4 by NiO's "memory-mapped Files" (memory-mapped Files) "To replace it. Generally more on Android, for breakpoints to download files.consider whether to use "memory mapped files" instead of 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 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 Rf.seek (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.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.
Import Java.io.RandomAccessFile; Import Java.nio.MappedByteBuffer; Import Java.nio.channels.FileChannel; 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 = Fc.map (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.
Applications of the Randomaccessfile class:
&NBSP;
/* * Program features: Demonstrates 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 {Randomaccessfil E 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 UT F string ");//This length is written at the first two bytes of the current file pointer, can be read File.writeboolean (true) by Readshort (), or 1 bytes file.writeshort (395);//Account 2 bytes File.writelong (2325451l);//Account for 8 bytes File.writeutf ("Again a UTF string"); File.writefloat (35.5f);//accounted for 4 bytes file.writechar (' a ');//accounted for 2 bytes file.seek (0);//Set the position of the file pointer to the beginning of the file The following reads the data from the file file, paying attention to the position of the 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 ——————"); 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 done! "); } }
randomaccessfile Insert Write Example:
/** * * @param skip skips how many bytes are inserted into the data * @param str to insert the string * @pa Ram fileName File path */public static void 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--) {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 (); } }
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:
Import java.io.FileNotFoundException; Import java.io.IOException; Import Java.io.RandomAccessFile; /** * Test using multithreading for file writes */public class Test {public static void main (string[] args) throws E Xception {///pre-allocated file occupies disk space, a file of the specified size is created on 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 from a file of 3072 bytes to the new fileWritethread (1024*4,s4.getbytes ()). 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 a specified location in a file static class Filewritethread extends Th read{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 (); } catch (Exception e) {}}}}}
Java IO randomaccessfile Any location read/write