问题
I am having a string which needs to be sent as response from a servlet & I am having two approaches to send response back from it.
First is using PrintWriter.
response.getWriter().print(responseString);
Second is using OutputStream.
byte[] byteResponse = responseString.getBytes(Charset.forName("UTF-8"));
response.getOutputStream().write(byteResponse);
I want to know which is better and efficient way of sending response?
Please suggest.
回答1:
Use an OutputStream for binary data, and a Writer for text.
回答2:
I am having a string specifies that you wish to write a string so i suggest the PrintWriter object
//prints text data to screen (browser)
PrintWriter printer = response.getWriter();
printer.print(string);
//print again if you wish
printer.print("Welcome blahblah");
//close afterwards if you don't mind.
printer.close();
so if you wish to write text to browser, PrintWriter works just fine, fast and simple.
来源:https://stackoverflow.com/questions/26010650/servlet-response-write-vs-print-which-is-better