Thursday, March 12, 2015

Generating archives on-the-fly in server memory

TL;DR - String byte array > text file > ZipEntry > ZipOutput > ByteArrayOutput > ServletOutput.

Looking into generating a jar file (essentially a zip archive), with a single text file within, that contains dynamically generated data, I located this and this which I'm attempting to combine for use.

The first part is straightforward; generating the content into the zip file as a ZipEntry with an explicit file name, all done in memory.

        try {
            String contents = "SomeStringA=SomeStringB";
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(baos);
            ZipEntry entry = new ZipEntry("file.txt");
            zos.putNextEntry(entry);            zos.write(contents.getBytes(StandardCharsets.UTF_8));//or just "UTF-8" if you're on Java 6
            zos.closeEntry();
            zos.close();//The archive needs to know it is done
        } catch (IOException e) {
            e.printStackTrace();
        }

The second part, I'm still mucking around a bit. This snippet should work... but I have yet to test this out. I'll update again once it is confirmed.

         response.setContentType("application/zip");         response.setHeader("Content-Disposition", "attachment; filename=\"file.jar\"");
         response.getOutputStream().write(baos.toByteArray());
         response.getOutputStream().flush();

Of course, all this is going to be done in a servlet method the is expecting a response output, to which the zip file will be churned out to (as a JAR file). Don't forget to flush()!

Edit: After running through the actual stuff, I realise that the ZipOutputStream needs to be closed as the final action. The code snippet above is pretty much spot on otherwise.

No comments:

Post a Comment