Java Realizes Arbitrary Copy Mode of InputStream

  • 2021-12-04 10:07:47
  • OfStack

Any copy of Java InputStream

Sometimes, when we need to use the same InputStream many times, how to realize the copy use of InputStream

We can convert InputStream to ByteArrayOutputStream first. Then you can clone any InputStream you want

The code is as follows:


ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > -1 ) {
    baos.write(buffer, 0, len);
}
baos.flush();
 
//  Open 1 New input streams 
InputStream is1 = new ByteArrayInputStream(baos.toByteArray()); 
InputStream is2 = new ByteArrayInputStream(baos.toByteArray());

But if you really need to keep an original input stream to receive information, you need to capture the close () method of the input stream for related operations

Copy the code of InputStream stream


private static InputStream 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 new ByteArrayInputStream(baos.toByteArray());
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Related articles: