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: 
I know this question is answered but if you have a list of strings and you want to create a separate file for each string in the archive, you can use the snippet below.

```
public void zipFileTest() throws IOException {

    Map<String, String> map = Map.ofEntries(
            new AbstractMap.SimpleEntry<String, String>("File1.txt", "File1 Content"),
            new AbstractMap.SimpleEntry<String, String>("File2.txt", "File2 Content"),
            new AbstractMap.SimpleEntry<String, String>("File3.txt", "File3 Content")
    );

    createZipFileFromStringContents(map, "archive.zip");

}

public void createZipFileFromStringContents(Map<String, String> map, String zipfilePath) throws IOException {

    FileOutputStream fout = new FileOutputStream(zipfilePath);
    ZipOutputStream zout = new ZipOutputStream(fout);

    for (Map.Entry<String, String> entry : map.entrySet()) {
        String fileName = entry.getKey();
        ZipEntry zipFile = new ZipEntry(fileName);
        zout.putNextEntry(zipFile);
        String fileContent = entry.getValue();
        zout.write(fileContent.getBytes(), 0, fileContent.getBytes().length);
        zout.closeEntry();
    }

    zout.close();
}

```

It will create a zip file with the structure as in the below image:

[![zip file structure](https://i.stack.imgur.com/1QzP6.png)](https://i.stack.imgur.com/1QzP6.png)
```
public static void zipFromTxt(String zipFilePath, String txtFilePath) {
    Assert.notNull(zipFilePath, "Zip file path is required");
    Assert.notNull(txtFilePath, "Txt file path is required");
    zipFromTxt(new File(zipFilePath), new File(txtFilePath));
}

public static void zipFromTxt(File zipFile, File txtFile) {
    ZipOutputStream out = null;
    FileInputStream in = null;
    try {
        Assert.notNull(zipFile, "Zip file is required");
        Assert.notNull(txtFile, "Txt file is required");
        out = new ZipOutputStream(new FileOutputStream(zipFile));
        in = new FileInputStream(txtFile);
        out.putNextEntry(new ZipEntry(txtFile.getName()));
        int len;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            out.flush();
        }
    } catch (Exception e) {
        log.info("Zip from txt occur error,Detail message:{}", e.toString());
    } finally {
        try {
            if (in != null) in.close();
            if (out != null) {
                out.closeEntry();
                out.close();
            }
        } catch (Exception e) {
            log.info("Zip from txt close error,Detail message:{}", e.toString());
        }
    }
}

```