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)
Since it took me a while to figure it out, I thought it would be helpful to post my solution using Java 7+ ZipFileSystem 

```
 openZip(runFile);

 addToZip(filepath); //loop construct;  

 zipfs.close();

 private void openZip(File runFile) throws IOException {
    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    env.put("encoding", "UTF-8");
    Files.deleteIfExists(runFile.toPath());
    zipfs = FileSystems.newFileSystem(URI.create("jar:" + runFile.toURI().toString()), env);    
 }

 private void addToZip(String filename) throws IOException {
    Path externalTxtFile = Paths.get(filename).toAbsolutePath();
    Path pathInZipfile = zipfs.getPath(filename.substring(filename.lastIndexOf("results"))); //all files to be stored have a common base folder, results/ in my case
    if (Files.isDirectory(externalTxtFile)) {
        Files.createDirectories(pathInZipfile);
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(externalTxtFile)) {
            for (Path child : ds) {
                addToZip(child.normalize().toString()); //recursive call
            }
        }
    } else {
        // copy file to zip file
        Files.copy(externalTxtFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING);            
    }
 }

```