美文网首页
BtyeBuffer 转InputStream

BtyeBuffer 转InputStream

作者: 宋雾代 | 来源:发表于2019-03-01 17:38 被阅读0次

    很遗憾,目前JDK并没有提供有效的途径转换。查了很多资料,曾经看到网上有人说使用以下方法:

    public void byteBuffer(){
        ByteBuffer buf = ByteBuffer.allocate(100);
        buf.clear();
        InputStream inputStream = new ByteArrayInputStream(buf.array());
    }
    

    但是这个方法是不对的,因为ByteBuffer的array方法返回的字符串并不是到limit的内容而是整个容量(cap)。

    正确的做法是实现自己的InputStream,以下给大家参考:

    public class ByteBufferBackedInputStream extends InputStream {
        private ByteBuffer buf;
        public ByteBufferBackedInputStream(ByteBuffer buf){
            this.buf = buf;
        }
        public int read() throws IOException{
            if(!buf.hasRemaining()){
                return -1;
            }
            return buf.get()& 0xFF;
        }
        public int read(byte[] bytes,int off,int len)throws IOException{
            if(!buf.hasRemaining()){
                return -1;
            }
            len = Math.min(len,buf.remaining());
            buf.get(bytes,off,len);
            return len;
        }
    }
    

    相关文章

      网友评论

          本文标题:BtyeBuffer 转InputStream

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