您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将InputStream写入HttpServletResponse

将InputStream写入HttpServletResponse

只需编写块,而不是先将其完全复制到Java内存中即可。下面的基本示例以10KB的块为单位编写。这样,您最终只能获得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);
    }
}

作为性能方面的极品,您可以使用NIOChannels和直接分配的ByteBuffer。在某些自定义实用程序类中创建以下实用程序/帮助程序方法,例如Utils

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());
Jave 2022/1/1 18:19:28 有451人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶