输入流的合并---SequenceInputStream

  整体思路:将多个输入流InputStream在逻辑上拼接成一个大的输入流,依次读取每个流,如下图所示;

在这里插入图片描述

关键代码分析

  • 初始化时,设置要合并的输入流集合e和当前要读取的输入流in;
  • 读取数据时,如果当前流结束,则读取下个输入流;
public SequenceInputStream(Enumeration<? extends InputStream> e) {
        this.e = e;
        try {
            nextStream();
        } catch (IOException ex) {
            // This should never happen
            throw new Error("panic");
        }
    }
   
   /**
     *  Continues reading in the next stream if an EOF is reached.
     */
    final void nextStream() throws IOException {
        if (in != null) {
            in.close();
        }

        if (e.hasMoreElements()) {
            in = (InputStream) e.nextElement();
            if (in == null)
                throw new NullPointerException();
        }
        else in = null;
    }
    
	public int read() throws IOException {
        while (in != null) {
            int c = in.read();
            if (c != -1) {
                return c;
            }
            nextStream();
        }
        return -1;
    }

使用示例

        String url = "http://10.88.128.23:8000/resource/ds_home_daily/lrp/t1";
        File file1 = new File("/Users/didi/Desktop/f1");
        InputStream inputStream1 = new FileInputStream(file1);
        File file2 = new File("/Users/didi/Desktop/f2");
        InputStream inputStream2 = new FileInputStream(file2);
        List<InputStream> list = new ArrayList<>(2);
        list.add(inputStream1); 
        list.add(inputStream2);
        Enumeration<InputStream> eum = Collections.enumeration(list);
        SequenceInputStream sis = new SequenceInputStream(eum);
        HttpResponseResult httpResponseResult = HttpClientUtils.postStream(url, "UTF-8","filecontent", sis, "files2", null);
        String responseBody = httpResponseResult.getResponseBody();
        System.out.println(responseBody);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值