溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java實(shí)現(xiàn)inputstream流的復(fù)制代碼實(shí)例

發(fā)布時(shí)間:2020-09-25 18:47:03 來源:腳本之家 閱讀:175 作者:薛柏梁 欄目:編程語言

這篇文章主要介紹了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í)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(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)容。

AI