流关闭以进行StreamingOutput

时间:2019-01-10 10:57:46

标签: stream

我正在尝试根据传入的输入流编写构建流输出响应,这是我的代码

public static void writeToResponse(final Response.ResponseBuilder response, final InputStream input, final String fileContentType, String fileName, final boolean isDownload, final boolean sanitizeXss) throws PreviewException {
    InputStream newInput;
    try {
        response.encoding(UTF_8);
        if (!StringUtils.isBlank(fileContentType)) {
            response.type(fileContentType);
        }
        if (isDownload) {
            if (fileName == null) fileName = "";
            response.header("Content-Disposition", "attachment; filename=\"" + fileName + '"');
        }
        if (logger.isDebugEnabled())
            logger.debug(String.format("Sanitize xss is = %b", sanitizeXss));
        if (sanitizeXss) {
            final String html = IOUtils.toString(input, UTF_8);
            IOUtils.closeQuietly(input);
            final String newHtml = XssUtils.cleanHtml(html);
            newInput = IOUtils.toInputStream(newHtml, UTF_8);
        } else {
            newInput = input;
        }
        final InputStream stream = newInput;
        response.entity((StreamingOutput) outputStream -> {
            try {
                IOUtils.copy(stream, outputStream);
            } finally {
                IOUtils.closeQuietly(stream);
            }
        });
    } catch (Exception ex) {
        throw new PreviewException(ex);
    }
}

上面的代码有效,但是如果我关闭输入流,则会在 IOUtils.copy(stream,outputStream)行表示流已关闭。

错误代码如下 〜与上述相同的代码

response.entity((StreamingOutput) outputStream -> {

                IOUtils.copy(stream, outputStream);

        });
    } catch (Exception ex) {
        throw new PreviewException(ex);
    } finally {
        IOUtils.closeQuietly(input);
    }

0 个答案:

没有答案