Browse DevX
Sign up for e-mail newsletters from DevX


Stream Both Character and Binary Data via a Servlet : Page 2

Writing a servlet that can perform character streaming is easy, but streaming binary content is trickier. This simple six-step tutorial guides you through a streaming solution that enables you to stream both character and binary data.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Step One
Set the appropriate MIME type based on the format with which you're working. The getMimeType() method supports various MIME types:

/* * This Method Returns the right MIME type for a particular format * <p> * @param String format ex: xml or HTML etc. * @return String MIMEtype */ private String getMimeType(String format) { if(format.equalsIgnoreCase("pdf")) //check the out type return "application/pdf"; else if(format.equalsIgnoreCase("audio_basic")) return "audio/basic"; else if(format.equalsIgnoreCase("audio_wav")) return "audio/wav"; else if(format.equalsIgnoreCase("image_gif")) return "image/gif"; else if(format.equalsIgnoreCase("image_jpeg")) return "image/jpeg"; else if(format.equalsIgnoreCase("image_bmp")) return "image/bmp"; else if(format.equalsIgnoreCase("image_x-png")) return "image/x-png"; else if(format.equalsIgnoreCase("msdownload")) return "application/x-msdownload"; else if(format.equalsIgnoreCase("video_avi")) return "video/avi"; else if(format.equalsIgnoreCase("video_mpeg")) return "video/mpeg"; else if(format.equalsIgnoreCase("html")) return "text/html"; else if(format.equalsIgnoreCase("xml")) return "text/xml"; else return null; }

Step Two
Get the reference to the right OutPutStream. Use ServletOutPutStream, where as for character data you'd use PrintWriter, the java.io class that prints objects to a text-output stream. This following snippet is for binary data:

ServletOutputStream sOutStream = response.getOutputStream();

Step Three
Create BufferedInputStream from the InputStream:

BufferedInputStream bis = null; InputStream in = urlc.getInputStream(); bis = new BufferedInputStream(in);

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date