Log in

How to write ZIP file using pipe and nio - Денис Цыплаков [entries|archive|friends|userinfo]
Денис Цыплаков

[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

How to write ZIP file using pipe and nio [Aug. 7th, 2009|10:40 am]
Денис Цыплаков
[mood |productive]

Task - we need to create zip file in servlet container and put it into servlet outputstream without storing the whole zip file in memory or HDD.

package test;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

 * Author: Denis Tsyplakov Datetime: Aug 7, 2009 9:33:42 AM
public class PipeDemo {

    static Logger log = Logger.getLogger(PipeDemo.class.getName());

    public static void main(String[] argv)
            throws Exception {
        FileOutputStream fos = new FileOutputStream("C:\\tmp\\1.zip");
        try {
            Pipe pipe = Pipe.open();

            WritableByteChannel out = Channels.newChannel(fos);

            ZipStreamWriter worker = new ZipStreamWriter(pipe.sink());

            ReadableByteChannel workerChannel = (pipe.source());
            ByteBuffer buffer = ByteBuffer.allocate(1024*8);

            while (workerChannel.read(buffer) >= 0) {
        finally {

    private static class ZipStreamWriter extends Thread {
        WritableByteChannel channel;

        ZipStreamWriter(WritableByteChannel channel) {
            this.channel = channel;

        public void run() {
            try {
                ZipOutputStream zos = new ZipOutputStream(Channels.newOutputStream(channel));
                try {
                    zos.putNextEntry(new ZipEntry("test.txt"));
                    zos.write("This is test file content".getBytes());
                finally {
            } catch (Exception e) {


From: sianamber
2009-12-13 12:45 pm (UTC)
С Днем Рождения!
(Reply) (Thread)
From: mutu26
2010-08-21 10:25 pm (UTC)
Like situation is very usual for me. I quite often with archives on my work. Luckily I found out the solution similar issues - repair zip file. I observed it on an one soft community. It impressed on me within minutes after I had extracted it on my PC. Probably it will be so effective for you.
(Reply) (Thread)