我有一个要写入 HttpServletResponse 的 InputStream。 有这种方法,由于使用了byte[],耗时太长
InputStream is = getInputStream();
int contentLength = getContentLength();
byte[] data = new byte[contentLength];
is.read(data);
//response here is the HttpServletResponse object
response.setContentLength(contentLength);
response.write(data);
我想知道在速度和效率方面最好的方法是什么。
最佳答案
只需分 block 写入,而不是先将其完全复制到 Java 的内存中。下面的基本示例将其写入 10KB 的 block 中。通过这种方式,您最终只会使用 10KB 的一致内存,而不是完整的内容长度。此外,最终用户将更快地开始获取部分内容。
response.setContentLength(getContentLength());
byte[] buffer = new byte[10240];
try (
InputStream input = getInputStream();
OutputStream output = response.getOutputStream();
) {
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
作为性能方面的精华,您可以使用 NIO Channels
和一个直接分配的 ByteBuffer
.在一些自定义实用程序类中创建以下实用程序/帮助程序方法,例如工具
:
public static long stream(InputStream input, OutputStream output) throws IOException {
try (
ReadableByteChannel inputChannel = Channels.newChannel(input);
WritableByteChannel outputChannel = Channels.newChannel(output);
) {
ByteBuffer buffer = ByteBuffer.allocateDirect(10240);
long size = 0;
while (inputChannel.read(buffer) != -1) {
buffer.flip();
size += outputChannel.write(buffer);
buffer.clear();
}
return size;
}
}
然后您可以按如下方式使用:
response.setContentLength(getContentLength());
Utils.stream(getInputStream(), response.getOutputStream());
关于java - 将 InputStream 写入 HttpServletResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10142409/