0

I am writing a server in JAVA, where client requests to download multiple files and server will create a ZipOutputStream and serve immediately. On the other hand another thread will write to ZipOutputStream. I used piped input/output stream.

Code

PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
in.connect(out);
ZipOutputStream zout = new ZipOutputStream(out);
new Thread{
  public void run(){
       while(condition){
           more logic.. 
           zout.write(data,0,length);
           zout.flush()
       }
       zout.close();
       out.close();
  }
}.start();
return in;

But when I click download button it download(finish immediately) a small file(corrupted) while my zip creating job is still running. How can I synchronize these two job?

Community
  • 1
  • 1
shantanu
  • 2,408
  • 2
  • 26
  • 56

1 Answers1

0

You should flush and then close ZipOutputStream. And better use ZipEntry to create archive

    ZipOutputStream zout = new ZipOutputStream(out);
    new Thread {
        public void run () {
            while (condition) {
                // logic ...
                zipEntry = new ZipEntry("name");
                zout.putNextEntry(zipEntry);
                zout.write(data);
                zout.flush();
                zout.closeEntry();
            }
            zout.flush();
            zout.close();
        }
    }.start();

    return in;
Ataur Rahman Munna
  • 3,887
  • 1
  • 23
  • 34
  • I exactly did the same code. I didn't use flush and closeEntry methods first time. But using those methods also didn't help. – shantanu Apr 21 '16 at 09:10