My requirement is to create 2 copies of the inputstream, one for Apache Tika File MimeType Detect and another to Output Stream.
private List<InputStream> copyInputStream(final InputStream pInputStream, final int numberOfCopies) throws UploadServiceException{
final int bytesSize = 8192;
List<InputStream> isList = null;
try(PushbackInputStream pushIS = new PushbackInputStream(pInputStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();){
byte[] buffer = new byte[bytesSize];
for (int length = 0; ((length = pushIS.read(buffer)) > 0);) {
baos.write(buffer, 0, length);
}
baos.flush();
isList = new ArrayList();
for(int i = 0; i < numberOfCopies ; i++){
isList.add(new ByteArrayInputStream(baos.toByteArray()));
}
} catch (IOException ex) {
throw new MyException(ErrorCodeEnum.IO_ERROR, ex);
} catch (Exception ex) {
throw new MyException(ErrorCodeEnum.GENERIC_ERROR, ex);
}
return isList;
}
I see some performance issues
- The size of the byte array is twice the file size. I planned on using the ByteArrayOutputStream(int size) but I don't have the file size during the upload.
- I see the garbage collection is not happening very often, how does one handle such cases.
UPDATE
Based on the feedback
- Removed PushbackInputStream
Added final byte[] byteArrayIS = baos.toByteArray();
private List<InputStream> copyInputStream(final InputStream pInputStream, final int numberOfCopies) throws MyException{ final int bytesSize = 8192; List<InputStream> isList = null; try(ByteArrayOutputStream baos = new ByteArrayOutputStream();){ byte[] buffer = new byte[bytesSize]; for (int length = 0; ((length = pInputStream.read(buffer)) > 0);) { baos.write(buffer, 0, length); } baos.flush(); isList = new ArrayList(); final byte[] byteArrayIS = baos.toByteArray(); for(int i = 0; i < numberOfCopies ; i++){ isList.add(new ByteArrayInputStream(byteArrayIS)); } } catch (IOException ex) { throw new MyException(ErrorCodeEnum.IO_ERROR, ex); } catch (Exception ex) { if(ex instanceof MyException){ throw ex; } throw new MyException(ErrorCodeEnum.GENERIC_ERROR, ex); } return isList; }