将 InputStream 写入 HttpServletResponse [英] Write an InputStream to an HttpServletResponse

查看:46
本文介绍了将 InputStream 写入 HttpServletResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要写入 HttpServletResponse 的 InputStream.有这个方法,由于使用byte[]

I have an InputStream that I want written to a HttpServletResponse. There's this approach, which takes too long due to the use of 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);

我想知道在速度和效率方面什么可能是最好的方法.

I was wondering what could possibly be the best way to do it, in terms of speed and efficiency.

推荐答案

只需在块中写入,而不是先将其完全复制到 Java 的内存中.下面的基本示例将其写入 10KB 的块中.通过这种方式,您最终只会使用 10KB 的一致内存,而不是完整的内容长度.此外,最终用户将更快地开始获取部分内容.

Just write in blocks instead of copying it entirely into Java's memory first. The below basic example writes it in blocks of 10KB. This way you end up with a consistent memory usage of only 10KB instead of the complete content length. Also the enduser will start getting parts of the content much sooner.

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.在一些自定义实用程序类中创建以下实用程序/助手方法,例如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());

这篇关于将 InputStream 写入 HttpServletResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆