Can someone tell me how to clone an inputstream, taking as little creation time as possible? I need to clone an inputstream multiple times for multiple methods to process the IS. I've tried three ways and things don't work for one reason or another.
Method #1: Thanks to the stackoverflow community, I found the following link helpful and have incorporated the code snippet in my program.
However, using this code can take up to one minute (for a 10MB file) to create the cloned inputstreams and my program needs to be as fast as possible.
int read = 0;
byte[] bytes = new byte[1024*1024*2];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((read = is.read(bytes)) != -1)
bos.write(bytes,0,read);
byte[] ba = bos.toByteArray();
InputStream is1 = new ByteArrayInputStream(ba);
InputStream is2 = new ByteArrayInputStream(ba);
InputStream is3 = new ByteArrayInputStream(ba);
Method #2: I also tried using BufferedInputStream to clone the IS. This was fast (slowest creation time == 1ms. fastest == 0ms). However, after I sent is1 to be processed, the methods processing is2 and is3 threw an error saying there was nothing to process, almost like all 3 variables below referenced the same IS.
is = getFileFromBucket(path,filename);
...
...
InputStream is1 = new BufferedInputStream(is);
InputStream is2 = new BufferedInputStream(is);
InputStream is3 = new BufferedInputStream(is);
Method #3: I think the compiler is lying to me. I checked markSupported() for is1 for the two examples above. It returned true so I thought I could run
is1.mark()
is1.reset()
or just
is1.reset();
before passing the IS to my respective methods. In both of the above examples, I get an error saying it's an invalid mark.
I'm out of ideas now so thanks in advance for any help you can give me.
P.S. From the comments I've received from people, I need to clarify a couple things regarding my situation: 1) This program is running on a VM 2) The inputstream is being passed into me from another method. I'm not reading from a local file 3) The size of the inputstream is not known