Java read files are buffered using Mappedbytebuffer

Source: Internet
Author: User

Java read files are buffered using Mappedbytebuffer, which ensures that the side reads large files and handles them.


Package Sean;import Java.io.bytearrayinputstream;import Java.io.file;import java.io.randomaccessfile;import Java.nio.mappedbytebuffer;import Java.nio.channels.filechannel;import Java.util.scanner;public class Snippet { public void Readresource () {Long filelength = 0;final int buffer_size = 0x300000;//3M buffer//for (String Filedirectory:thi S.readresourcedirectory ())//Get the file storage path, I use a method here to read out the file//storage path from the XML file, of course, you can also use the absolute path to replace the Filedriectory//{file file = new File ("D:\\mydata.txt"); filelength = File.length (); try {mappedbytebuffer inputbuffer = new Randomaccessfile (file, "R"). Getchannel (). Map (FileChannel.MapMode.READ_ONLY, 0,filelength);//Read large file byte[] dst = new byte[buffer_size];// Read the contents of 3M each time for (int offset = 0; offset < filelength; offset + = Buffer_size) {if (Filelength-offset >= buffer_size) { for (int i = 0; i < buffer_size; i++) Dst[i] = Inputbuffer.get (offset + i);} else {for (int i = 0; i < Filelength-offset; i++) Dst[i] = Inputbuffer.get (offset + i);} Will get the 3M content to scanner, here's XXX refers to the Scanner parsed delimiter Scanner scan = new Scanner (new Bytearrayinputstream (DST)). Usedelimiter (""); while (Scan.hasnext ()) {// Here is the method for parsing the read text System.out.print (Scan.next () + "");} Scan.close ();}} catch (Exception e) {e.printstacktrace ();} }}public static void Main (string[] args) {Snippet sp = new Snippet (); Sp.readresource ();}}


Java read files are buffered using Mappedbytebuffer

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.