且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java Servlet未写入响应字节

更新时间:2023-12-04 16:13:58

您没有刷新 BufferedOutputStream -因此它正在缓冲所有数据.您应该刷新那个,而不是 ServletOutputStream .

You're not flushing the BufferedOutputStream - so it's buffering all your data. You should flush that, not the ServletOutputStream.

但是,如果您只写一个字节数组,则无论如何都没有必要使用 BufferedOutputStream -而且您也不需要显式刷新,因为关闭会刷新.因此,您只需要:

However, if you're only writing a single byte array, there's no point in using BufferedOutputStream anyway - and you shouldn't need to explicitly flush anyway, as closing will flush. So you just need:

ServletOutputStream sos = response.getOutputStream();
sos.write(pdfBytes);
// Unclear whether *this* is needed, either.
sos.close();

我本人会期望 servlet容器来关闭输出流,但是从文档中尚不清楚.如果发生异常是否要关闭它是另一回事...

I'd personally expect the servlet container to close the output stream, but it's not clear from the docs. Whether you want to close it if an exception occurs is a different matter...