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();
}

```
There is another option by using `zip4j` at <https://github.com/srikanth-lingala/zip4j>

Creating a zip file with single file in it / Adding single file to an existing zip

`new ZipFile("filename.zip").addFile("filename.ext");`
 Or

`new ZipFile("filename.zip").addFile(new File("filename.ext"));`

Creating a zip file with multiple files / Adding multiple files to an existing zip

`new ZipFile("filename.zip").addFiles(Arrays.asList(new File("first_file"), new File("second_file")));`

Creating a zip file by adding a folder to it / Adding a folder to an existing zip

`new ZipFile("filename.zip").addFolder(new File("/user/myuser/folder_to_add"));`

Creating a zip file from stream / Adding a stream to an existing zip
`new ZipFile("filename.zip").addStream(inputStream, new ZipParameters());`