I have this program which I am trying to use to create a zip file of the file located in the directory.
The program runs but in chrome it fails to download by saying the network error.
In Mozilla, it says Ut0ij4ld.ZIP.part could not be saved, because the source file could not be read.
what am I doing wrong, is there a better approach to do this?
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = "D:\\Test\\";
File directory = new File(path);
String[] files = directory.list();
//check if directories have files
if (files != null && files.length > 0) {
//create zip stream
byte[] zip = zipFiles(directory, files);
// Sends the response back to the user / browser with zip content
ServletOutputStream sos = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"DATA.ZIP\"");
sos.write(zip);
sos.flush();
}
request.setAttribute("DownloadMessage", "Successfully");
request.getRequestDispatcher("DownloadZipFile.jsp").forward(request, response);
}
private byte[] zipFiles(File directory, String[] files) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
byte bytes[] = new byte[4096];
for (String fileName : files) {
try (FileInputStream fis = new FileInputStream(directory.getPath()
+ "/" + fileName);
BufferedInputStream bis = new BufferedInputStream(fis)) {
zos.putNextEntry(new ZipEntry(fileName));
int bytesRead;
while ((bytesRead = bis.read(bytes)) != -1) {
zos.write(bytes, 0, bytesRead);
}
zos.closeEntry();
}
}
zos.flush();
baos.flush();
zos.close();
baos.close();
return baos.toByteArray();
}