MappedByteBuffer和FileChannel 進行大文件下載

MappedByteBuffer 繼承自ByteBuffer ,與 BufferReader等等類似,但是性能上比BufferReader這些高。

使用方法:

 private void writeToCaches(ResponseBody body,DownInfo info){

        RandomAccessFile randomAccessFile=null;
        FileChannel fileCahnnel=null;
        InputStream inputStream=null;

        File file=new File(info.getSavePath());
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try {
            long allLength = 0 == info.getCountLength() ? body.contentLength() : info.getReadLength() + body
                    .contentLength();

            randomAccessFile=new RandomAccessFile(file,"rwd"); //rwd 表示文件可讀寫
            fileCahnnel=randomAccessFile.getChannel();
            inputStream=body.byteStream(); 
            MappedByteBuffer byteBuffer=fileCahnnel.map(FileChannel.MapMode.READ_WRITE,info.getReadLength(), allLength - info.getReadLength());

            byte[] buffer=new byte[1024*4];
            int len;
            while((len=inputStream.read(buffer))!=-1){
                byteBuffer.put(buffer,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
                try {
                    if(inputStream!=null) {
                        inputStream.close();
                    }
                    if(fileCahnnel!=null){
                        fileCahnnel.close();
                    }
                    if(randomAccessFile!=null){
                        randomAccessFile.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
            }
        }

    }
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容