• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ByteArrayOutputStream

 
Bob Moranski
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, does anyone know what ByteArrayOutputStream do in the folowing code?
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class KeepAlive extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
ByteArrayOutputStream bytes = new ByteArrayOutputStrea(1024);
PrintWriter out = new PrintWriter(bytes, true);
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>Hello World</BIG>");
out.println("</BODY></HTML>");
res.setContentLength(bytes.size());
bytes.writeTo(res.getOutputStream()); }}
 
Kevin Mukhar
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The ByteArrayOutputStream is a class that takes an output stream and writes the bytes from the stream to a byte array. If you have used a FileOutputStream, the concept is similar. When you write to a FileOutputStream, the bytes are written to a file.
The reason the code snippet uses a ByteArrayOutputStream is that the array can be used to determine the content length (2nd to last line) before the output is actually sent to the client (last line).
 
Bob Moranski
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, can you tell me why should content length be set? What does it benefit? Also, where on the client does the byte array from ByteArrayOutputStream go?
Thank you.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13077
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can get away with not setting content length for plain HTML. However, if you are sending some other resource - such as an zip file, image or sound data - the browser typically needs that length in order to process the resource correctly.
In the example given, the byte array is written after the response headers and is interpreted on the browser as "text/html".
Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic