java 如何在同一个 servlet 请求中使用 getOutputStream() 和 getWriter()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4321979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use getOutputStream() and getWriter() in the same servlet request?
提问by faree
How do I use getOutputStream() and getWriter() in the same servlet request?
如何在同一个 servlet 请求中使用 getOutputStream() 和 getWriter()?
回答by Martin Algesten
You can't use them both at the same time. If you first did getOutputStream()
you can't consequently in the same request do getWriter()
and vice versa. You can however wrap your ServletOuptputStream
in a PrintWriter
to get the same kind of writer you would have from getWriter()
.
您不能同时使用它们。如果你getOutputStream()
先做了getWriter()
,你就不能在同一个请求中做,反之亦然。但是,您可以将您的包裹ServletOuptputStream
在 a 中PrintWriter
以获得与您相同的作家getWriter()
。
ServletOutputStream out = response.getOutputStream();
// Notice encoding here, very important that it matches that of
// response.setCharacterEncoding();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
Another solution to not using getWriter()
is to use a PrintStream
which is somewhat similar, but then you don't have type compatibility with Writer
or PrintWriter
.
不使用的另一种解决方案getWriter()
是使用 a PrintStream
,它有点相似,但是您没有与Writer
or 的类型兼容性PrintWriter
。
// Encoding again very important to match that of your output.
PrintStream print = new PrintStream(os, true, "utf-8");
回答by user207421
You can use them both, just not at the same time, or rather not for the same response. If you need to use a Writer after you've already started using the OutputStream, just wrap an OutputStreamWriter around the output stream. However if you need to use an output stream after you've already used the writer you can't. You could always get the output stream first, wrap the writer around it as above, do your Writing, flush, then do your output streaming.
您可以同时使用它们,只是不要同时使用,或者不要用于相同的响应。如果您在开始使用 OutputStream 后需要使用 Writer,只需在输出流周围包装一个 OutputStreamWriter。但是,如果您在已经使用过编写器后需要使用输出流,则不能。您始终可以先获取输出流,如上所述将编写器包裹在其周围,然后进行编写、刷新,然后进行输出流处理。