【发布时间】:2017-08-08 09:32:57
【问题描述】:
我的要求是创建 2 个输入流副本,一个用于 Apache Tika File MimeType Detect,另一个用于输出流。
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;
}
我发现一些性能问题
- 字节数组的大小是文件大小的两倍。我计划使用 ByteArrayOutputStream(int size) 但在上传期间我没有文件大小。
- 我看到垃圾收集并不经常发生,如何处理这种情况。
更新
根据反馈
- 移除 PushbackInputStream
-
添加了最终字节[] 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; }
【问题讨论】:
-
'字节数组的大小是文件大小的两倍'怎么测?其实什么字节数组?你为什么要使用
ByteArrayOutputStream?将一个输入流复制到两个输出流并不难:编写TeeOutputStreamclass 很简单。 -
我用VisualVM监控。
-
监控什么?
-
监控CPU,堆大小,byte[] size used
-
我重复一遍。您通过这种方式测量了什么字节数组?
标签: java performance inputstream apache-tika bytearrayoutputstream