输入流的合并---SequenceInputStream

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangguosb/article/details/84027338

  整体思路:将多个输入流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);

猜你喜欢

转载自blog.csdn.net/yangguosb/article/details/84027338