美文网首页
Java构造指定大小的InputStream

Java构造指定大小的InputStream

作者: 魂之挽歌w | 来源:发表于2019-10-18 22:22 被阅读0次

构造指定大小的InputStream我第一个想到的就是使用SequenceInputStream进行拼接:方案一:

   /**
     * 获取指定大小的输入流
     * @param streamLength 流大小
     * @return InputSream
     */
    public static InputStream getInputStreamByLength(long streamLength) {
        int chunkSize = 500 * 1024 * 1024;
        if (streamLength <= chunkSize) {
            return new ByteArrayInputStream(new byte[(int) streamLength]);
        } else {
            int chunkCount = (int) Math.ceil(streamLength / (double) chunkSize);
            ByteArrayInputStream chunkInputStream = new ByteArrayInputStream(new byte[chunkSize]);
            if (chunkCount == 2) {
                ByteArrayInputStream second_stream = new ByteArrayInputStream(new byte[(int) (streamLength - chunkSize)]);
                return new SequenceInputStream(chunkInputStream, second_stream);
            }
            Vector<InputStream> vector = new Vector<InputStream>();
            for (int i = 0; i < chunkCount-1; i++) {
                vector.addElement(chunkInputStream);
            }
            vector.addElement(new ByteArrayInputStream(new byte[(int) (streamLength-(chunkCount-1)*chunkSize)]));
            Enumeration<InputStream> e = vector.elements();
            return new SequenceInputStream(e);
        }
    }

实际上只需要简单如下重写下read方法就行(太菜了我还是,还好),方案二:


    long length = 1024;
    int pos = 0;

    public MyInputStream(long length) {
        this.length = length;
    }

    public void setLength(long length){
        this.length =length;
    }
    @Override
    public int read() throws IOException {
        return pos == length ? -1 : pos++;
    }
}

相关文章

网友评论

      本文标题:Java构造指定大小的InputStream

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