Search code examples
javasocketsnetwork-programmingzipoutputstream

ZipOutputStream creating corrupt (unzippable) zip file


I am trying to send zipped bytes to another server and then have that server receive them and write out the zipped filed. When I do the zipping and writing on the same server it works great. The local version looks something like this:

ZipOutputStream zout = new ZipOutputStream(FileOutputStream);
zout.write(byteBuffer, 0, len);
zout.flush()
FileOutputStream.flush();
zout.close();

The cross server implementation creates a bad output though. The sending code is: (magic string tells the server it has received all of the data.

ZipOutputStream zout = new ZipOutputStream(out);
ZipEntry entry = new ZipEntry(fileName);
zout.putNextEntry(entry);
System.out.println("sending zipped bytes...");
zout.write(inputBuffer, contentBegin, len);
zout.flush();
zout.closeEntry();
out.flush();

byte[] magicStringData = "--------MagicStringCSE283Miami".getBytes("US-ASCII");
out.write(magicStringData, 0, magicStringData.length);
out.flush();    

System.out.println("Done writing file and sending zipped bytes.");

Thread.sleep(10000);
zout.close();
clntSock.close();  // Close the socket.  We are done with this client!

The receiving code looks like this:

        System.out.println("receiving zipped bytes...");
        byte[] inputBuffer = new byte[BUF_SIZE];
        int total2 = 0, count = 0;
        while(count != -1) { // read from origin's buffer into byteBuffer until origin is out of data
            count = inFromCompression.read(inputBuffer, total2, BUF_SIZE - total - 1);
            String msg = new String(inputBuffer, total2, count, "US-ASCII");
            total2 += count;
            if(msg.contains("-------MagicString")){
                System.out.println("full message received...");
                break;
            }
        }

        String inputString = new String(inputBuffer, 0, total2, "US-ASCII");
        int contentEnd = inputString.indexOf("--------MagicString");
        FileOutputStream fout2 = new FileOutputStream(outputFileName + ".zip");
        fout2.write(inputBuffer, 0, contentEnd);
        fout2.flush();
        fout2.close();

        System.out.println("Done writing zipped bytes.");

        //Thread.sleep(10000);
        //socketToCompression.close();

Any ideas? I am thinking it might be something like I am not closing the ZipOutputStream before sending the magic string that signals the end of the data, but every time I call zout.close() immediately after flushing zout it closes the entire socket.


Solution

  • Get rid of the magic string and just send and receive the actual data. You're presently throwing away any buffer that contains the magic string, including whatever ZIP data may have been before it.

    You don't need a ByteArrayOutputStream.