How to send data to client in binary form using ServletOutputStream?
import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath = "D:\\ratna\\RoseindiaHospital.zip"; String fileName = "RoseindiaHospital.zip"; FileInputStream fileToDownload = new FileInputStream(filePath); ServletOutputStream output = response.getOutputStream(); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); ByteArrayOutputStream output1 = new ByteArrayOutputStream(); int readBytes = 0; byte[] buffer = new byte[10000]; while ((readBytes = fileToDownload.read(buffer, 0, 10000)) != -1) { output.write(buffer, 0, readBytes); output1.write(buffer, 0, readBytes); } output.flush(); output.close(); fileToDownload.close(); } }
Description: - Servletoutputstream is used for sending data to client in binary format. It is retrieved via response.getOutputStream() function. ServletOutputStream is an abstract class and servlet container implements it. When you use character conversion and there is a lot of text then it is better to use byte[] instead of String object. ByteArrayOutputStream implements output stream and it contain data in form of byte array.For retrieving data you can use toByteArray() and toString() methods.
I need retrieve byte array in servlet ,could you explain me that?
Ads