Question: I have a dynamic text file that picks content from a database according to the user's query. I have to write this content into a text file and zip it in a folder in a servlet. How should I do this?

Answer: 
Spring boot controller, zip the files in a directory, and can be downloaded.

```
@RequestMapping(value = "/files.zip")
@ResponseBody
byte[] filesZip() throws IOException {
    File dir = new File("./");
    File[] filesArray = dir.listFiles();
    if (filesArray == null || filesArray.length == 0)
        System.out.println(dir.getAbsolutePath() + " have no file!");
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    ZipOutputStream zipOut= new ZipOutputStream(bo);
    for(File xlsFile:filesArray){
        if(!xlsFile.isFile())continue;
        ZipEntry zipEntry = new ZipEntry(xlsFile.getName());
        zipOut.putNextEntry(zipEntry);
        zipOut.write(IOUtils.toByteArray(new FileInputStream(xlsFile)));
        zipOut.closeEntry();
    }
    zipOut.close();
    return bo.toByteArray();
}

```
If you want decompress without software better use this code. Other code with pdf files sends error on manually decompress

```java
byte[] buffer = new byte[1024];

try {

   FileOutputStream fos = new FileOutputStream("123.zip");
   ZipOutputStream zos = new ZipOutputStream(fos);
   ZipEntry ze= new ZipEntry("file.pdf");
   zos.putNextEntry(ze);

   FileInputStream in = new FileInputStream("file.pdf");
   int len;

   while ((len = in.read(buffer)) > 0) {
      zos.write(buffer, 0, len);
   }

   in.close();
   zos.closeEntry();
   zos.close();

} catch(IOException ex) {
   ex.printStackTrace();
}

```