Java implementation of InputStream stream replication __java

Source: Internet
Author: User

After you get to a inputstream, you may want to use it more than once to perform a read operation. Because the stream read once can not read again, and the InputStream object itself can not replicate, and it does not implement the Cloneable interface, so you have to do something.

Realize the idea:

1, first convert the InputStream into Bytearrayoutputstream

2, later to use the InputStream object, and then from the Bytearrayoutputstream back

The code implementation is as follows:

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 ();
		
		Here you can write the stream you get bytearrayoutputstream BAOs = Cloneinputstream (input);  
		Open two new input streams 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; }
	}

}

This applies to some streams that are not very large, because the cache stream consumes memory.


Note: about why InputStream cannot be read repeatedly.

Interested can take a look at this article: http://blog.csdn.net/dreamtdp/article/details/26733563

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.