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();
            }
        }

    }

你可能感兴趣的:(MappedByteBuffer和FileChannel 进行大文件下载)