public static InputStream cloneContent ( InputStream source , int readbackSize , ByteArrayOutputStream target ) throws IOException { if ( source == null ) { return null ; } // if the source supports mark/reset then we read and then reset up to the read-back size if ( source . markSupported ( ) ) { readbackSize = Math . max ( TEN_KB , readbackSize ) ; // at least 10 KB (minimal waste, handles those -1 ContentLength cases) source . mark ( readbackSize ) ; copyContentIntoOutputStream ( source , target , readbackSize , false ) ; source . reset ( ) ; return source ; } else { copyContentIntoOutputStream ( source , target , ONE_MB , true ) ; byte [ ] fullContentBytes = target . toByteArray ( ) ; // if we can't reset the source we need to create a replacement stream so others can read the content return new ByteArrayInputStream ( fullContentBytes ) ; } }
used when you want to clone a InputStream s content and still have it appear rewound to the stream beginning