美文网首页
MappedByteBuffer和FileChannel 进行大

MappedByteBuffer和FileChannel 进行大

作者: Qy_huang | 来源:发表于2017-12-22 10:40 被阅读0次

    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 进行大

          本文链接:https://www.haomeiwen.com/subject/khjtgxtx.html