Package com.yao.bigfile;Import java.io.File;Import java.io.IOException;Import Java.io.RandomAccessFile;Import Java.nio.MappedByteBuffer;Import Java.nio.channels.FileChannel;PublicClass Readbig {PublicStaticFinal String FileName ="D://log//192.168.56.1_debug_.log_2014-12-04";PublicStaticvoid Main (string[] args)Throws IOException {Finalint buffer_size =0x300000;Buffer size is 3MFileFile =NewFile (FileName);/** * Map (filechannel.mapmode mode,long position, long size) mode-* Map files based on read-only, read/write, or private (copy-on-write), respectively, Filechannel.mapmode The READ_ONLY, read_write, or PRIVATE position-the location in the file as defined in the class, where the mapping area begins; must be a non-negative number * size-the area to be mapped; must be non-negative and not greater than integer.max_v Alue * So if you want to read the second half of the file, as in the example, if you want to read the text after 1 */8 content, you need to write this map (FileChannel.MapMode.READ_ONLY, * f.length () *7/8,f.length ()/8) * Want to read all the contents of the file, need to write this map (FileChannel.MapMode.READ_ONLY, 0,f.length ()) */Randomaccessfile RAF =New Randomaccessfile (File"R"); Mappedbytebuffer InputBuffer = Raf.getchannel (). Map (FileChannel.MapMode.READ_ONLY,File.length ()/2, File.length ()/2);byte[] DST =NewByte[buffer_size];Read 3M content at a timeLong start = System.currenttimemillis ();for (int offset =0; Offset < inputbuffer.capacity (); Offset + = buffer_size) {if (inputbuffer.capacity ()-offset >= buffer_size) {for (int i =0; i < buffer_size; i++) Dst[i] = Inputbuffer.get (offset + i); }else {for (int i = 0; i < inputbuffer.capacity ()-offset; i++) dst[i] = Inputbuffer.get (offset + i); } int length = (inputbuffer.capacity ()% Buffer_size = = 0)? BUFFER_SIZE:inputBuffer.capacity ()% Buffer_size; System.out. println (new String (DST, 0, length)); The new //String (Dst,0,length) allows you to remove the cached string and manipulate it.} raf.close (); Long end = System.currenttimemillis (); System.out. println ("reads the file file half of the content spent:" + (End-start) + "milliseconds");}}
Java NiO reads large files