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