Java實現inputstream流的複製__Java

來源:互聯網
上載者:User

擷取到一個inputstream後,可能要多次利用它進行read的操作。由於流讀過一次就不能再讀了,而InputStream對象本身不能複製,而且它也沒有實現Cloneable介面,所以得想點辦法。

實現思路:

1、先把InputStream轉化成ByteArrayOutputStream

2、後面要使用InputStream對象時,再從ByteArrayOutputStream轉化回來

代碼實現如下:

package com.test;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;public class StreamOperateUtil {public static void main(String[] args) throws FileNotFoundException { InputStream input =  new FileInputStream("c:\\test.txt"); //InputStream input =  httpconn.getInputStream(); //這裡可以寫你擷取到的流ByteArrayOutputStream baos = cloneInputStream(input);// 開啟兩個新的輸入資料流  InputStream stream1 = new ByteArrayInputStream(baos.toByteArray());  InputStream stream2 = new ByteArrayInputStream(baos.toByteArray());}private static ByteArrayOutputStream cloneInputStream(InputStream input) {try {ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len;while ((len = input.read(buffer)) > -1) {baos.write(buffer, 0, len);}baos.flush();return baos;} catch (IOException e) {e.printStackTrace();return null;}}}

這種適用於一些不是很大的流,因為緩衝流是會消耗記憶體的。


備忘:關於InputStream為什麼不能被重複讀取。

有興趣的可以看看這篇文章:http://blog.csdn.net/dreamtdp/article/details/26733563

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.