您好,登錄后才能下訂單哦!
這篇文章主要介紹了Java實(shí)現(xiàn)inputstream流的復(fù)制代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
獲取到一個(gè)inputstream后,可能要多次利用它進(jìn)行read的操作。由于流讀過一次就不能再讀了,而InputStream對(duì)象本身不能復(fù)制,而且它也沒有實(shí)現(xiàn)Cloneable接口,所以得想點(diǎn)辦法。
實(shí)現(xiàn)思路:
1、先把InputStream轉(zhuǎn)化成ByteArrayOutputStream
2、后面要使用InputStream對(duì)象時(shí),再?gòu)腂yteArrayOutputStream轉(zhuǎn)化回來
代碼
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); // 打開兩個(gè)新的輸入流 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; } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。