How do I use getOutputStream() and getWriter() in

2019-02-15 21:30发布

问题:

How do I use getOutputStream() and getWriter() in the same servlet request?

回答1:

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().

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.

// Encoding again very important to match that of your output.
PrintStream print = new PrintStream(os, true, "utf-8");


回答2:

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.