NiO in Java (ii)

Source: Internet
Author: User

One, Memory file mapping

Memory file mapping allows us to create and modify files that are too large to fit in memory. With the memory file mapping, we can assume that the entire file is in memory and that it can be accessed entirely as an array.

 PackageCom.dy.xidian;ImportJava.io.RandomAccessFile;ImportJava.nio.MappedByteBuffer;ImportJava.nio.channels.FileChannel; Public classLargemappedfiles {Static intLength = 0x8ffffff;  Public Static voidMain (string[] args)throwsException {@SuppressWarnings ("Resource") Mappedbytebuffer out=NewRandomaccessfile ("Test.dat", "RW"). Getchannel (). Map (FileChannel.MapMode.READ_WRITE,0, length);  for(inti = 0; i < length; i++) Out.put (byte) ' X '); System.out.println ("Finished writing");  for(inti = LENGTH/2; I < LENGTH/2 + 6; i++) System.out.print (Char) Out.get (i)); }}

The 0 in map indicates the mapping from the beginning of the file, and the size of the map is length (128MB). The Mappedbytebuffer is a direct buffer (the JVM directly performs IO operations on the contents of the direct buffer, and if the buffer is not direct, the JVM will first copy the data from the user buffer to its own buffer and IO operation to its own buffer).

So mappedbytebuffer to large files faster than normal IO stream. Mappedbytebuffer inherits from Bytebuffer, so our operations on Bytebuffer are applicable to Bytebuffer.

Second, the mapping file part of the lock

File mappings are typically applied to extremely large files. We may need to partially lock this huge file so that other processes can modify portions of the file that are not locked. For example: The database is like this, so multiple users can access it at the same time

 PackageCom.dy.xidian;Importjava.io.IOException;ImportJava.io.RandomAccessFile;ImportJava.nio.ByteBuffer;ImportJava.nio.MappedByteBuffer;ImportJava.nio.channels.FileChannel;ImportJava.nio.channels.FileLock; Public classLockingmappedfiles {Static Final intLENGTH = 0x8ffffff; StaticFileChannel FC; @SuppressWarnings ("Resource")     Public Static voidMain (string[] args)throwsException {FC=NewRandomaccessfile ("Test.dat", "RW"). Getchannel (); Mappedbytebuffer out=FC. Map (FileChannel.MapMode.READ_WRITE,0, LENGTH);  for(inti = 0; i < LENGTH; i++) Out.put (byte) ' X '); NewLockandmodify (out, 0, LENGTH/3); NewLockandmodify (out, LENGTH/2, LENGTH/2 + LENGTH/4); }    Private Static classLockandmodifyextendsThread {PrivateBytebuffer Buff; Private intstart, end; Lockandmodify (Bytebuffer buff,intStartintend) {            Super();  This. Start =start;  This. end =end;  This. Buff =Buff;            Buff.limit (end);            Buff.position (start); //Create a new buffer identity object//the Position=0,limit and capacity of the object equals the number of bytes remaining in the original buffer. Buff =Buff.slice ();        Start (); }         Public voidrun () {Try {                //gets the lock on the channel, specifying the starting and ending positions of the lock//To set a lock to an exclusive lockFilelock fl = Fc.lock (Start, End,false); System.out.println ("Locked:" + start + "to" +end);  while(Buff.position () < Buff.limit ()-1) Buff.put (byte) (Buff.get () + 1));                Fl.release (); System.out.println ("Released:" + Start + "to" +end); } Catch(IOException e) {Throw NewRuntimeException (e); }        }    }}
Example of 3.GZIP usage
 PackageCom.dy.xidian;ImportJava.io.BufferedOutputStream;ImportJava.io.BufferedReader;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.FileReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.util.zip.GZIPInputStream;ImportJava.util.zip.GZIPOutputStream; Public classgzipcompress { Public Static voidMain (string[] args)throwsIOException {if(Args.length = = 0) {System.out.println ("Usage: \n\tgzipcompress file\n" + "\tuses GZIP compress to compress" + "the file T o test.gz "); System.exit (1); } BufferedReader in=NewBufferedReader (NewFileReader (args[0])); Bufferedoutputstream out=NewBufferedoutputstream (NewGzipoutputstream (NewFileOutputStream ("test.gz"))); System.out.println ("Writing file"); intC;  while((c = In.read ())! = 1) {out.write (c);        } in.close ();        Out.close (); System.out.println ("Reading file"); BufferedReader in2=NewBufferedReader (NewInputStreamReader (NewGzipinputstream (NewFileInputStream ("test.gz"))));        String s;  while((s = in2.readline ())! =NULL) System.out.println (s);    In2.close (); }}

NiO in Java (ii)

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.