ZipOutputStream创建损坏的(可解压缩的)zip文件

时间:2015-05-09 04:18:37

标签: java sockets networking zipoutputstream

我正在尝试将压缩字节发送到另一台服务器,然后让该服务器接收它们并写出压缩文件。当我在同一台服务器上进行压缩和编写时,它的效果非常好。本地版本看起来像这样:

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

但跨服务器实现会创建一个错误的输出。发送代码是:(魔术字符串告诉服务器它已收到所有数据。

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!

接收代码如下所示:

        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();

有什么想法吗?我想这可能是因为我没有在发送表示数据结束的魔术字符串之前关闭ZipOutputStream,但每次在刷新zout后立即调用zout.close()它会关闭整个套接字。

1 个答案:

答案 0 :(得分:0)

摆脱魔法字符串,只发送和接收实际数据。您现在丢弃了包含魔术字符串的任何缓冲区,包括之前可能存在的任何ZIP数据。

您不需要ByteArrayOutputStream.